<?php

use \GatewayWorker\Lib\Gateway;
class User{

    //生成随机字串
    public static function createCode($type,$length){
        global $utility;
        $verifyCode = "1234";
        if ($type == 1) {
            $verifyCode = implode('', range(0, 9));
        }elseif ($type == 2) {
            $verifyCode = implode('', array_merge(range('a', 'z'),range('A', 'Z')));
        }else{
            $verifyCode = implode('', array_merge(range('a', 'z'),range(0, 9),range('A', 'Z')));
        }
        //打乱字符串
        $verifyCode = str_shuffle($verifyCode);
        $verify = substr($verifyCode, 0, 6);
        $utility->redisSetEx('verify_'.md5($verify), $verify, 120);
        return array(
            'state' => 200,
            'verify' => $verify,
        );
    }

    public static function redPacketRound()
    {
        global $utility;
        return $utility->redPacketRound(10, 5);
    }

    # region 设置用户的返点
    public static function setUserRebate($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd",
            'rebate|F',
            'uno'
        );
        $paras = $utility->get_url_args($paras, $url_args);
        $tablename = \Config\Sys::$dbprefix . "users";

        $result = array('state'=>404, 'msgid'=>10006,'cmd'=>$paras['cmd']);

        if(empty($paras['token']))
        {
            return $result;
        }
        if(empty($paras['uno']))
        {
            return $result;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            return array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
        }else {
            # 检测用户是不是自己的直属下级
            $sql = "SELECT `uid`,`parentid`,`nickname`,`rebate` FROM `" . $tablename . "` WHERE `uno`='" . $paras['uno'] . "' LIMIT 1";
            $myuser = $db->row($sql);

            if ($myuser && $myuser['parentid'] == $user['uid']) {
                # 检测下属返点是否小于当前用户的极差后的最大值
                $minrebatevalue = $utility->getSystemParams('minrebatevalue');
                $maxrebatevalue = (floatval($user['rebate']) - floatval($minrebatevalue));

                # 如果有下级用户了，返水就不能低于当前值
                $sql = "SELECT COUNT(1) AS _TOTAL FROM `".$tablename."` WHERE `parentid`=".$myuser['uid'];
                $haveUser = $db->row($sql);

                if($haveUser['_TOTAL'] > 0 && floatval($myuser['rebate']) > floatval($paras['rebate'])){
                    $result['msgid'] = 10114;// 返点值不正确;
                    $result['msg'] = '当前用户已有直属玩家，不能小于当前的 ' . $myuser['rebate'] . '% 返点';
                    return $result;
                }

                if (floatval($paras['rebate']) > $maxrebatevalue) {
                    $result['msgid'] = 10114;// 返点值不正确;
                    $result['msg'] = '返点值须在 0% - ' . $maxrebatevalue . '% 之间';
                    return $result;
                }
                if(floatval($paras['rebate']) == floatval($myuser['rebate'])){
                    $result['msgid'] = 10114;// 返点值不正确;
                    $result['msg'] = '保存失败，返点值与之前相同！';
                    return $result;
                }
                $sql = "UPDATE `" . $tablename . "` SET `rebate`=" . $paras['rebate'] . " WHERE `uid`=" . $myuser['uid'] . " LIMIT 1";
                $db->query($sql);
                $result = array(
                    'state' => 200,
                    'msgid' => 200,
                    'msg' => '用户' . $paras['uno'] . '（' . $myuser['nickname'] . '）的返点【' . $paras['rebate'] . '%】设置成功',
                );
            }
        }
        return $result;
    }
    # endregion
    # region 绑定手机号码
    public static function setUserMobile($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd",
            'tel',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['token']))
        {
            return $data;
        }
        if(empty($paras['tel']))
        {
            $data['msgid'] = 10061;
            return $data;
        }
        if(!$utility->isMobileNumber($paras['tel']))
        {
            $data['msgid'] = 10061;
            return $data;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }
        # 已绑定手机就不能再绑定了
        if(!empty($user['tel']))
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>404,
                'msgid'=>10064
            );
            return $data;
        }
        # 检测手机号码是否绑定过其它帐号
        $sql = 'SELECT `tel` FROM `'.\Config\Sys::$dbprefix.'users` WHERE `tel`='.$paras['tel'].' LIMIT 1';
        $data = $db->row($sql);
        if($data){
            $result = array(
                'cmd' => $paras['cmd'],
                'state' => 404,
                'msgid' => 10062,
            );
            return $result;
        }
        if(!empty($user['tel'])){
            $result = array(
                'cmd' => $paras['cmd'],
                'state' => 404,
                'msgid' => 10064,
            );
            return $result;
        }
        # 保存到数据库
        $db->query("UPDATE `".\Config\Sys::$dbprefix."users` SET `tel`='".$paras['tel']."' WHERE `uid`=".$user['uid']." LIMIT 1");
        return array(
            'state' => 200,
            'cmd'   => $paras['cmd'],
            'tel'   => $paras['tel'],
        );

    }
    # endregion

    # region 更新玩家昵称
    public static function updateUserNickname($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'nickname',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['nickname']))
        {
            $result['msgid'] = 10043;
            return $result;
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            if($paras['nickname'] == $user['nickname']){
                $result['msgid'] = 10044;
                return $result;
            }
            # 查找昵称是否有一样的
            $sql = "SELECT COUNT(1) AS _TOTAL FROM `".\Config\Sys::$dbprefix."users` WHERE `nickname`='".$paras['nickname']."' LIMIT 1";
            $isNickname = $db->row($sql);
            if(intval($isNickname['_TOTAL']) > 0){
                $result = array(
                    'state' => 404,
                    'msgid' => 10113,
                    'cmd' => $paras['cmd'],
                );
            }else {
                # 保存到数据库
                $db->query("UPDATE `" . \Config\Sys::$dbprefix . "users` SET `nickname`='" . $paras['nickname'] . "' WHERE `uid`=" . $user['uid'] . " LIMIT 1");
                $result = array(
                    'state' => 200,
                    'cmd' => $paras['cmd'],
                );
            }
        }else{
            $result['state'] = $user['state'];
            $result['msgid'] = $user['msgid'];
        }
        return $result;
    }
    # endregion

    # region 更新玩家帐号
    public static function updateUserName($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'username',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['username']))
        {
            $result['msgid'] = 10009;
            return $result;
        }
        if(strlen($paras['username']) < 6)
        {
            $result['msgid'] = 10071;
            return $result;
        }
        # 检测用户名是否已被使用
        $sql = "SELECT `username` FROM `".\Config\Sys::$dbprefix."users` WHERE `username`='".$paras['username']."' LIMIT 1";
        $exists = $db->row($sql);
        if($exists){
            $result['msgid'] = 10012;
            return $result;
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            if(!empty($user['username'])){
                $result['msgid'] = 10063;
                return $result;
            }
            # 保存到数据库
            $db->query("UPDATE `".\Config\Sys::$dbprefix."users` SET `username`='".$paras['username']."' WHERE `uid`=".$user['uid']." LIMIT 1");
            $result = array(
                'state'=>200,
                'cmd'=>$paras['cmd'],
            );
        }else{
            $result['state'] = $user['state'];
            $result['msgid'] = $user['msgid'];
        }
        return $result;
    }
    # endregion

    # region 更新玩家QQ
    public static function updateUserQQ($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'qq',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['qq']))
        {
            $result['msgid'] = 10065;
            return $result;
        }
        # 检测是否已被使用
        $sql = "SELECT `qq` FROM `".\Config\Sys::$dbprefix."users` WHERE `qq`='".$paras['qq']."' LIMIT 1";
        $exists = $db->row($sql);
        if($exists){
            $result['msgid'] = 10067;
            return $result;
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            if(!empty($user['qq'])){
                $result['msgid'] = 10067;
                return $result;
            }
            # 保存到数据库
            $db->query("UPDATE `".\Config\Sys::$dbprefix."users` SET `qq`='".$paras['qq']."' WHERE `uid`=".$user['uid']." LIMIT 1");
            $result = array(
                'state'=>200,
                'cmd'=>$paras['cmd'],
            );
        }else{
            $result['state'] = $user['state'];
            $result['msgid'] = $user['msgid'];
        }
        return $result;
    }
    # endregion

    # region 更新玩家微信
    public static function updateUserWX($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'wx',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['wx']))
        {
            $result['msgid'] = 10068;
            return $result;
        }
        # 检测是否已被使用
        $sql = "SELECT `wx` FROM `".\Config\Sys::$dbprefix."users` WHERE `wx`='".$paras['wx']."' LIMIT 1";
        $exists = $db->row($sql);
        if($exists){
            $result['msgid'] = 10070;
            return $result;
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            if(!empty($user['wx'])){
                $result['msgid'] = 10070;
                return $result;
            }
            # 保存到数据库
            $db->query("UPDATE `".\Config\Sys::$dbprefix."users` SET `wx`='".$paras['wx']."' WHERE `uid`=".$user['uid']." LIMIT 1");
            $result = array(
                'state'=>200,
                'cmd'=>$paras['cmd'],
            );
        }else{
            $result['state'] = $user['state'];
            $result['msgid'] = $user['msgid'];
        }
        return $result;
    }
    # endregion

    # region 列出系统头像
    public static function systemAvatarList()
    {
        global $utility;
        return array(
            'state'=>200,
            'data'=>$utility->roundAvatarList(),
        );
    }
    # endregion

    # region 更新用户登录密码
    public static function updateUserPassword($paras){
        global $utility;
        global $db;

        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'oldpasswd',
            'newpasswd',
            'newrepawd',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $result = array('state'=>404, 'msgid'=>404);
        if(empty($paras['oldpasswd'])){
            $result['msgid'] = 10098;
            return $result;
        }
        if(empty($paras['newpasswd'])){
            $result['msgid'] = 10099;
            return $result;
        }
        if($paras['newpasswd'] != $paras['newrepawd']){
            $result['msgid'] = 10105;
            return $result;
        }

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']!=200){
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }



        //查询用户是否存在
        $fields = "`passwd`, `token`";
        $tablename = '`'.\Config\Sys::$dbprefix.'users`';
        $sql = "SELECT {$fields} FROM {$tablename} WHERE `uid`='{$user['uid']}' LIMIT 1";
        $userRe = $db->row($sql);
        $makePasswd = $utility->encrypt($paras['oldpasswd'],'E',$userRe['token']);
        if ($userRe['passwd'] != $makePasswd) {
            $result['msgid'] = 10097;//帐号密码不正确
        }else{
            //生成密码token
            $token = $utility->randString(4);
            $makePasswd = $utility->encrypt($paras['newpasswd'], 'E', $token);
            $args['passwd'] = $makePasswd;
            $args['token'] = $token;
            $db->query("UPDATE `rp_users` SET `token`='".$token."',`passwd`='".$makePasswd."',`webtoken`='' WHERE `uid`=".$user['uid']." LIMIT 1");
            $result = array(
                'state' => 200,
                'msgid' => 10102,
            );
        }
        return $result;

    }
    # endregion

    # region 更新头像
    public static function updteUserheader($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'base64header',
            'imgurl',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']!=200){
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }

        $result = array('state'=>404, 'msgid'=>404);

        if(!empty($paras['imgurl'])){
            $db->query("UPDATE `" . \Config\Sys::$dbprefix . "users` SET `avatar`='" . $paras['imgurl'] . "' WHERE `uid`=" . $user['uid'] . " LIMIT 1");
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'headurl' => $paras['imgurl'],
            );
        }else {
            $base64_image_content = $paras['base64header'];
            //匹配出图片的格式
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $res)) {
                $type = $res[2];
                $file_dir = date('YmdHis', time());
                $new_file = __DIR__ . Config\Sys::$imgs_upload_dir . "avatar/" . $file_dir . "/";
                if (!file_exists($new_file)) {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($new_file, 0755);
                    chgrp($new_file, Config\Sys::$sysrun_group);
                    chown($new_file, Config\Sys::$sysrun_user);
                }
                $new_file = $new_file . $user['uno'] . '.' . $type;
                if (file_put_contents($new_file, base64_decode(str_replace($res[1], '', $base64_image_content)))) {
                    $avatar = "avatar/" . $file_dir . "/" . $user['uno'] . '.' . $type;
                    $result = array(
                        'state' => 200,
                        'cmd' => $paras['cmd'],
                        'headurl' => $avatar,
                    );
                    # 保存到数据库
                    $db->query("UPDATE `" . \Config\Sys::$dbprefix . "users` SET `avatar`='" . $avatar . "' WHERE `uid`=" . $user['uid'] . " LIMIT 1");
                    chgrp($new_file, Config\Sys::$sysrun_group);
                    chown($new_file, Config\Sys::$sysrun_user);
                } else {
                    $result = array(
                        'state' => 404,
                        'cmd' => $paras['cmd'],
                        'msgid' => 10042,//文件上传失败
                    );
                }
            }
        }
        return $result;
    }
    # endregion

    # region 收货地址设置
    public static function receivingAddressList($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd"
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['token']))
        {
            return $data;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }
        $sql = "SELECT `id`,`name`,`tel`,`address`,`default` FROM `".\Config\Sys::$dbprefix."receiving_address` WHERE `uid`={$user['uid']}";
        $data = $db->query($sql);
        return array(
            'cmd' => $paras['cmd'],
            'state' => 200,
            'data' => $data,
        );
    }
    public static function receivingAddressSetDefault($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd",
            'id|N',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['token']))
        {
            return $data;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }
        $sql = "UPDATE `".\Config\Sys::$dbprefix."receiving_address` SET `default`=1 WHERE `id`={$paras['id']} AND `uid`={$user['uid']} LIMIT 1";
        $db->query($sql);
        return array(
            'cmd' => 'receivingaddresssetdefault',
            'state' => 200,
            'msgid' => 200,
        );
    }
    public static function receivingAddressDelete($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd",
            'id|N',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['token']))
        {
            return $data;
        }
        if(empty($paras['id'])){
            return $data;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }
        $sql = "DELETE FROM `".\Config\Sys::$dbprefix."receiving_address` WHERE `id`={$paras['id']} AND `uid`={$user['uid']} LIMIT 1";
        $db->query($sql);
        return array(
            'cmd' => 'receivingaddressdelete',
            'state' => 200,
            'msgid' => 10057,
        );
    }
    public static function receivingAddressAddSave($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd",
            'name',
            'tel',
            'address',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);
        # region 条件参数检测
        if(empty($paras['token']))
        {
            return $data;
        }
        if(empty($paras['name']))
        {
            $data['msgid'] = 10058; //收件人姓名不能为空
            return $data;
        }
        if(empty($paras['tel']))
        {
            $data['msgid'] = 10059; //收件人电话不能为空
            return $data;
        }
        if(!$utility->isMobileNumber($paras['tel']))
        {
            $data['msgid'] = 10061;
            return $data;
        }
        if(empty($paras['address']))
        {
            $data['msgid'] = 10060; //收件人地址不能为空
            return $data;
        }
        # endregion
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }

        $add_log = array(
            'name' => $paras['name'],
            'tel' => $paras['tel'],
            'address' => $paras['address'],
            'uid' => $user['uid'],
        );
        $db->insert(\Config\Sys::$dbprefix.'receiving_address')->cols($add_log)->query();
        return array(
            'cmd' => 'receivingaddressaddsave',
            'state' => 200,
            'msgid' => 200,
        );
    }
    public static function receivingAddressEditSave($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            "token",
            "cmd",
            'name',
            'tel',
            'address',
            'editid',
        );
        $paras = $utility->get_url_args($paras, $url_args);
        //print_r($paras);
        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);
        # region 条件参数检测
        if(empty($paras['token']))
        {
            return $data;
        }
        if(empty($paras['name']))
        {
            $data['msgid'] = 10058; //收件人姓名不能为空
            return $data;
        }
        if(empty($paras['tel']))
        {
            $data['msgid'] = 10059; //收件人电话不能为空
            return $data;
        }
        if(!$utility->isMobileNumber($paras['tel']))
        {
            $data['msgid'] = 10061;
            return $data;
        }
        if(empty($paras['address']))
        {
            $data['msgid'] = 10060; //收件人地址不能为空
            return $data;
        }
        # endregion
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }

        $edit_log = array(
            'name' => $paras['name'],
            'tel' => $paras['tel'],
            'address' => $paras['address'],
        );

        $db->update(\Config\Sys::$dbprefix.'receiving_address')->cols($edit_log)->where('id='.$paras['editid'])->query();
        $data = array(
            'cmd' => $paras['cmd'],
            'state'=>200,
            'msgid'=>200
        );
        return $data;
    }
    # endregion

    # region 所有银行列表
    public static function bankLists(){
        global $db;
        global $utility;
        $sql = "SELECT `id`,`title` FROM `".\Config\Sys::$dbprefix."bank_list` WHERE `state`=1 ORDER BY `sort` ASC";
        $datas = $db->query($sql);
        $result = array(

        );
        foreach($datas as $k=>$v)
        {
            $result[$v['id']] = $v['title'];
        }

        return [
            'state' => 200,
            'cmd' => '',
            'datas' => $result,
        ];
    }
    # endregion

    # region 用户收款银行设置
    public static function delUserBank($paras){
        return array(
            'cmd' => 'deluserbank',
            'state' => 200,
            'msgid' => 10056,
        );
    }
    public static function editUserBank($paras)
    {
        return array(
            'cmd' => 'deluserbank',
            'state' => 200,
            'msgid' => 10056,
        );
    }
    public static function setUserBank($paras)
    {
        global $db;
        global $utility;

        $url_args = array(
            'cmd',
            'token',
            'name',
            'account',
            'openadds',
            'bankid|N',
        );
        $paras = $utility->get_url_args($paras, $url_args);
        // print_r($paras);
        $data = array('state'=>404, 'msgid'=>404,'cmd'=>$paras['cmd']);
        if(empty($paras['token']) || empty($paras['name']) || empty($paras['account']) || empty($paras['bankid']))
        {
            return $data;
        }
        # 去除所有名字中的空格
        # $paras['name'] = $utility->onlyZH($paras['name']);// preg_replace('# #','', $paras['name']);
        /*
        if($paras['bankid']!=22 && $paras['bankid']!=23) {
            if (!$utility->isBankNumber($paras['account'])) {
                $data['msgid'] = 10053;
                return $data;
            }
        }
        */
        # 如果是支付宝即要检测帐号是不是手机号码或是邮箱号码
        if($paras['bankid']==22){
            //if(!$utility->isMobileNumber($paras['account']) || !$utility->isEmail($paras['account']))
            //{
                //$data['msgid'] = 10072;
                //return $data;
            //}
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200){
            $data = array(
                'cmd' => $paras['cmd'],
                'state' => $user['state'],
                'msgid' => $user['msgid']
            );
            return $data;
        }
        //print_r($user);
        # 检测用户是否已经有设置过这个银行卡
        $sql = "SELECT COUNT(`id`) AS _TOTAL FROM `".\Config\Sys::$dbprefix."users_bank` WHERE `bankid`={$paras['bankid']} and `uid`={$user['uid']} and `isdelete`=0";
        $bankid = $db->row($sql);

        // print_r($bankid);

        if($bankid['_TOTAL']){
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>404,
                'msgid'=>10052 //同个银行只能设置一张银行卡
            );
            return $data;
        }

        # 一张卡及同姓名的不能绑定两个帐号
        $sql = "SELECT COUNT(`id`) AS _TOTAL FROM `".\Config\Sys::$dbprefix."users_bank` WHERE (`account`='{$paras['account']}' OR `name`='{$paras['name']}') AND `isdelete`=0";
        $bankid = $db->row($sql);
        if($bankid['_TOTAL']){
            $data = array(
                'cmd' => $paras['cmd'],
                'state'=>404,
                'msgid'=>10053 //同个银行只能设置一张银行卡
            );
            return $data;
        }

        $insert_log = array(
            'uid' => $user['uid'],
            'bankid' => $paras['bankid'],
            'name' => $paras['name'],
            'account' => $paras['account'],
            'openadds' => $paras['openadds'],
            'state' => 1,
            'isdelete' => 0,
        );
        $insert_id = $db->insert(\Config\Sys::$dbprefix.'users_bank')->cols($insert_log)->query();
        $data = array(
            'cmd' => $paras['cmd'],
            'state' => 404,
            'msgid' => 10055,
        );
        if($insert_id)
        {
            $data = array(
                'cmd' => $paras['cmd'],
                'state' => 200,
                'msgid' => 10054,
            );
        }
        //print_r($data);
        return $data;

    }
    # endregion

    # region 提现
    public static function userbanks($args)
    {
        global $db;
        global $utility;

        $url_args = array("token","cmd");
        $paras = $utility->get_url_args($args, $url_args);

        $data = array('state'=>404, 'msgid'=>404);

        if(empty($paras['token']))
        {
            return $data;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }
        $db_prefix = \Config\Sys::$dbprefix;
        # 取出用户设置的银行列表
        $fields = "b.`id`,b.`bankid`,b.`name`,b.`account`,b.`openadds`,l.`title` as bankname,lower(l.`code`) as code,REPLACE(l.`logo`,'/upload/','') as logo";
        $where = "l.`id`=b.`bankid` AND b.`uid`={$user['uid']} AND b.`state`=1 AND b.`isdelete`=0";
        $tablename = "`{$db_prefix}users_bank` b, `{$db_prefix}bank_list` l";
        $sql = "SELECT {$fields} FROM {$tablename} WHERE {$where}";

        # 取出待激活的赠送金额，提现须要扣除这个金额
        $givesql = "SELECT IFNULL(SUM(coin),0) AS _TOTAL FROM {$db_prefix}givecoinlog WHERE `uid`={$user['uid']} AND `liqtype` IN(23,25) AND `state`=0";
        $givecoin = $db->row($givesql);
        $givecoin = $givecoin['_TOTAL'];

        $data = array(
            'state' => 200,
            'banks' => $db->query($sql),
            'usercoin' => $user['usercoin'],
            'mincash' => $utility->getSystemParams('mincash'),
            'maxcash' => $utility->getSystemParams('maxcash'),
            'cashbegintime' => $utility->getSystemParams('cashbegintime'),
            'cashendtime' => $utility->getSystemParams('cashendtime'),
            'givecoin' => $givecoin,
        );

        return $data;
    }
    public static function userCash($args)
    {
        global $db;
        global $utility;

        $db_prefix = \Config\Json::$config['db_prefix'];

        $url_args = array(
            "amount|F",//提现金额
            "bankid|N",
            "token",
            "cmd",
        );
        $paras = $utility->get_url_args($args, $url_args);

        $data = array('state'=>404, 'msgid'=>404);

        if(empty($paras['token']) || empty($paras['amount']) || empty($paras['bankid']))
        {
            return $data;
        }
        # 用户登录是否有效
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']!=200)
        {
            $data = array(
                'state'=>$user['state'],
                'msgid'=>$user['msgid']
            );
            return $data;
        }
        if($user['usertype']==0)
        {
            $data = array(
                'state'=>404,
                'msgid'=>10085
            );
            return $data;
        }
        # 取出待激活的赠送金额，提现须要扣除这个金额
        //$givesql = "SELECT IFNULL(SUM(coin),0) AS _TOTAL FROM {$db_prefix}givecoinlog WHERE `uid`={$user['uid']} AND `liqtype` IN(23,25) AND `state`=0";
        //$givecoin = $db->row($givesql);
        //$givecoin = $givecoin['_TOTAL'];
        $givecoin = 0;

        $user['usercoin'] = $user['usercoin'] - $givecoin;

        $cashcoin = floatval($paras['amount']);
        # 检测用户的提现金额
        if($user['usercoin'] < $cashcoin)
        {
            $data['msgid'] = 10005;
            return $data;
        }
        # 检测用户的微信是否已设置
        if(empty($user['wx']) || empty($user['qq']) || empty($user['tel']))
        {
            $data['msgid'] = 10094;
            return $data;
        }

        # 提现限制 - 如果还有提现未处理的订单将退回提现申请
        $sql  = 'SELECT COUNT(1) AS _TOTAL FROM `'.\Config\Sys::$dbprefix.'users_cash` WHERE `uid`='.$user['uid'].' AND `state`=0';
        $haveCash = $db->row($sql);
        if($haveCash['_TOTAL']) {
            $data['msgid'] = 10109; // 后台要另加一个提示，你还有未处理的提现申请，请在上笔提现完成后再次申请
            return $data;
        }

        # 提现金额限制
        $mincash = $utility->getSystemParams('mincash');
        $maxcash = $utility->getSystemParams('maxcash');
        if ( $paras['amount'] < $mincash || $paras['amount'] > $maxcash ){
            $data['msgid'] = 10049;
            $data['mincash'] = $mincash;
            $data['maxcash'] = $maxcash;
            return $data;
        }

        # 提现次数限制
        $sql = 'SELECT `cashtimes` FROM `'.\Config\Sys::$dbprefix.'userlevel` WHERE `lid`='.$user['userlevel'].' LIMIT 1';
        $cashCountNums = $db->row($sql);

        $beginTimes = strtotime(date('Y-m-d',time()));
        $endTimes = $beginTimes + 86400;
        $sql  = 'SELECT COUNT(1) AS _TOTAL FROM `'.\Config\Sys::$dbprefix.'users_cash` WHERE `uid`='.$user['uid'] .' AND `cashtime`>='.$beginTimes.' AND `cashtime`<='.$endTimes .' AND `state`<>2';

        $haveCash = $db->row($sql);
        if($haveCash['_TOTAL'] >= $cashCountNums['cashtimes'])
        {
            $data['msgid'] = 10110; // 提现已达到限制次数
            return $data;
        }

        #检测流水是否满足提现要求 - 系统默认或是单个用户？
        # 实际的充值 = 充值 + 传进来的包 - 传出去的包 - 兑换消费的金额
        $userRechargeCoin =  $utility->userRealityRecharge($user['uid']);
        $mastbetcoin = floatval($userRechargeCoin['recharge']) * floatval($utility->getSystemParams('coinodds'));

        //if($user['usertype'] == 1 && floatval($user['betcoin']) < $mastbetcoin)

        if(floatval($user['betcoin']) < $mastbetcoin)
        {
            $data['state'] = 303;
            $data['msgid'] = 10073;
            $data['coin'] = $utility->formatCoin(($mastbetcoin - $user['betcoin']));
            return $data;
        }
        # 找出玩家提现所用的到帐银行帐号
        $sql = "SELECT b.*,l.`title` FROM `{$db_prefix}users_bank` b,`{$db_prefix}bank_list` l WHERE l.`id`=b.`bankid` AND b.`id`={$paras['bankid']} LIMIT 1";
        $bank = $db->row($sql);

        $paras['uid'] = $user['uid'];
        $paras['bankid'] = $paras['bankid'];
        $paras['bankname'] = $bank['title'];
        $paras['name'] = $bank['name'];
        $paras['account'] = $bank['account'];
        $paras['openadds'] = $bank['openadds'];
        $paras['usercoin'] = $user['usercoin'];
        $paras['nowtime'] = time();
        $paras['usertype'] = $user['usertype'];

        $db->beginTrans();
            # 记录提现记录
            $cashId = $utility->insertCashToDb($paras);
            # 记录帐变
            $coinLog = array(
                'uid' => $user['uid'],
                'gameid' => 0,
                'coin' => (0-$paras['amount']),
                'liqtype' => 20, // 提现
                'ex2' => $cashId,
            );
            $utility->setCoin($coinLog);
        $db->commitTrans();
        $data = array(
            'state' => 200,
            'msgid' => 10050,
            'bankname' => $bank['title'],
            'amount' => $paras['amount'],
            'orderid' => $cashId,
        );
        return $data;
    }
    # endregion

    # region 转送红包给玩家
    public static function sendToUserCoin($paras)
    {
        global $db;
        global $utility;

        $mastArgs = array(
            'cmd',
            'token',
            'sendcoin|F',
            'sendtouno',
        );

        $paras = $utility->get_url_args($paras, $mastArgs);

        $result = array('state'=>404, 'cmd'=>$paras['cmd']);

        # 传送红包的功能是否有开启
        $enableCharge = $utility->getSystemParams("enablechange");
        if(!$enableCharge){
            $result['msgid'] = 10111;//传红包功能已关闭
            return $result;
        }

        if(empty($paras['sendcoin'])){
            $result['msgid'] = 10018;//你的金币不足，请先充值
            return $result;
        }
        if(empty($paras['sendtouno'])){
            $result['msgid'] = 10039;//玩家编号不能为空
            return $result;
        }

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            // 试玩用户不能转送红包
            if($user['usertype']==0)
            {
                $result['state'] = 400;
                $result['msgid'] = 10085;
                return $result;
            }


            //登录成功
            $uid = $user['uid'];

            //发送方和接收方不能相同
            if ($user['uno'] == $paras['sendtouno']) {
                $result['msgid'] = 10019;//不能发红包给自己
                return $result;
            }

            #如果没有充值就不能传送红包
            if(empty($user['recharge'])){
                $result['msgid'] = 10107;
                return $result;
            }

            #检测流水是否满足提现要求
            $mastbetcoin = floatval($user['recharge']) * floatval($utility->getSystemParams('coinodds'));

            if(intval($user['usertype']) != 2){
                $result['state'] = 404;
                $result['msgid'] = 10096;
                return $result;
            }

            if($user['usertype'] == 1 && floatval($user['betcoin']) < $mastbetcoin)
            {
                $result['state'] = 303;
                $result['msgid'] = 10073;
                $result['coin'] = $utility->formatCoin(($mastbetcoin - floatval($user['betcoin'])));
                return $result;
            }
            $sendcoin = floatval($paras['sendcoin']);
            # 转帐限制
            # 取出待激活的赠送金额，提现须要扣除这个金额
            //$givesql = "SELECT IFNULL(SUM(coin),0) AS _TOTAL FROM `".\Config\Sys::$dbprefix."givecoinlog` WHERE `uid`={$user['uid']} AND `liqtype`=25 AND `state`=0";
            //$givecoin = $db->row($givesql);


            $givecoin = floatval($user['givecoin']) + floatval($user['reggivecoin']);//$givecoin['_TOTAL'];

            //$user['usercoin'] =


            # 后期：用户是不是自己的直属玩家，如果是直属玩家不限制
            /*
            if($user['agentlevel']<=0) {
                $enablecash = $utility->getUserRechargeAndGive($user['uid'], $paras);
                if ($enablecash['state'] != 200) {
                    return $enablecash;
                }
            }
            */
            # 2018-02-02 后期将限制传红包的接收者只能为自己的直属或所属下级玩

            # parents like '%%';
            # 找出接收方的资料
            $sql = "SELECT `uid`,`uno`,`nickname`,`parentid`,`usertype` FROM `".\Config\Sys::$dbprefix."users` WHERE `uno`='".$paras['sendtouno']."' LIMIT 1";

            $touser = $db->row($sql);

            if(!$touser)
            {
                $result['msgid'] = 10003;//帐号不存在
                return $result;
            }
            // 接收方不能是试玩用户
            if($touser['usertype']==0)
            {
                $result['state'] = 400;
                $result['msgid'] = 10085;
                return $result;
            }

            # 检测接收玩家是不是自己的上级、直属、下级或是同一代理线上的
            //$onlyDirect = $utility->getSystemParams('onlyDirect');
            $onlyDirect = false;
            if($onlyDirect){
                # 是不是上级
                $odWHere = " `uid`=".$touser['uid']." AND (`parents`=".$uid." OR FIND_IN_SET('".$uid."', `parents`))";
                $sql = "SELECT `uid`,`uno` FROM `".\Config\Sys::$dbprefix."users` WHERE ".$odWHere." LIMIT 1";

                $isuser = $db->query($sql);
                if(!$isuser)
                {
                    $result['msgid'] = 10081;//接收方与你没有相应的联系，无法直接传送！
                    return $result;
                }
            }
            //默认手续费率，需要从数据库中取
            $rate = floatval($utility->getSystemParams('changerate'));
            $ratecoin = $sendcoin * $rate / 100;
            //查找当前用户的可用金币
            //$user = $this->db->row("SELECT `coin` FROM `rp_users` WHERE `webtoken`='{$token}'");
            if ((floatval($user['usercoin'])-floatval($givecoin)) >= ($sendcoin+$ratecoin)) {
                #begion
                $db->beginTrans();
                //记发送方的帐变及更新发送方的余额
                $utility->setCoin(array(
                        'uid' => $user['uid'],
                        'coin' => (0 - $sendcoin),
                        'liqtype' => 12,
                        'ex1' => $touser['uid'],
                        'ex2' => $touser['uno'],
                        'ex3' => $touser['nickname'],
                    )
                );
                //记接收方的帐变及更新接收方的余额
                $utility->setCoin(array(
                        'uid' => $touser['uid'],
                        'coin' => $sendcoin,
                        'liqtype' => 14,
                        'ex1' => $user['uid'],
                        'ex2' => $user['uno'],
                        'ex3' => $user['nickname'],
                    )
                );
                # 记录发送方的记录
                $transfer_log = array(
                    'touid' => $touser['uid'],
                    'touno' => $touser['uno'],
                    'fromuid' => $user['uid'],
                    'fromuno' => $user['uno'],
                    'coin' => $sendcoin,
                    'rate' => $rate,
                    'times' => time(),
                    'state' => 1
                );
                $db->insert(\Config\Sys::$dbprefix.'transfer_log')->cols($transfer_log)->query();
                # 记接收方的记录
                # 接收方的的记录直接转换一下数据就可以了

                if($ratecoin > 0) {
                    $utility->setCoin(array(
                            'uid' => $user['uid'],
                            'coin' => (0 - $ratecoin),
                            'liqtype' => 13,
                            'ex1' => $touser['uid'],
                            'ex3' => $sendcoin . '×' . $rate . '%',
                        )
                    );
                }
                $db->commitTrans();
                $result['state'] = 200;
                $result['msgid'] = 10007;//玩家红包收取成功
                $result['ratecoin'] = $utility->formatCoin($ratecoin);
                //通知玩家收取红包
                $touidResult =  array(
                    'cmd' => 'fromusercoin',
                    'state' => 200,
                    'coin' => $sendcoin,
                    'ratecoin' => 0,
                    'fromname' => $user['nickname'],
                );
                # 组装数据，一条给发送方，一条给接收方
                $_result = array(
                    'state' => 200,
                    'cmd'=>$paras['cmd'],
                    'senderuno' => $user['uno'],
                    'receiveruno' => $touser['uno'],
                    'sender' => $result,
                    'receiver' => $touidResult,
                );
                return $_result;
                //Gateway::sendtouid($sendtouid, json_encode($touidResult));
                //Gateway::sendtouid($uid, json_encode($result));
                #endregion
            } else {
                $result['msgid'] = 10005;//你的金币不足，请先充值
                return $result;
            }
        }else{
            $result['state'] = $user['state'];
            $result['msgid'] = $user['msgid'];
            return $result;
        }
    }
    # endregion

    # region  推广链接管理
    public static function agentLinksAdd($args){
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            "cmd",
            "token",
            "rebate|F",
            "usertype|N",
        );
        $paras = $utility->get_url_args($args, $url_args);

        $result = array(
            'state'=>404,
            'msgid'=>404,
            'cmd'=>$paras['cmd']
        );

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if ($user['state'] == 200) {
            $sql = "SELECT COUNT(`id`) AS _TOTAL FROM `".\Config\Sys::$dbprefix."agentlinks` WHERE `rebate`=".$paras['rebate']." LIMIT 1";
            $links = $db->row($sql);
            if($links['_TOTAL'] <= 0) {
                $minrebatevalue = $utility->getSystemParams('minrebatevalue');
                $maxrebatevalue = (floatval($user['rebate']) - floatval($minrebatevalue));

                if($maxrebatevalue >= $paras['rebate']) {
                    $sql = " INSERT INTO `" . \Config\Sys::$dbprefix . "agentlinks` (`uid`,`usertype`,`rebate`,`actiontimes`) VALUES(".$user['uid'].",".$paras['usertype']."," . $paras['rebate'] . ",".time().")";
                    $db->query($sql);
                    $result = array(
                        'state' => 200,
                        'msgid' => 200,
                        'msg' => '推广链接添加成功',
                    );
                }else{
                    $result = array(
                        'state' => 404,
                        'msgid' => 404,
                        'msg' => '返点设置错误，须在 0% - '.$maxrebatevalue.'%之间',
                    );
                }
            }else{
                $result = array(
                    'state' => 404,
                    'msgid' => 404,
                    'msg' => '推广链接所属不明，无法操作',
                );
            }
        }
        return $result;
    }
    public static function agentLinksEdit($args){
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            "cmd",
            "token",
            "lid|N",
            "rebate|F",
        );
        $paras = $utility->get_url_args($args, $url_args);

        $result = array(
            'state'=>404,
            'msgid'=>404,
            'cmd'=>$paras['cmd']
        );

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if ($user['state'] == 200) {
            $sql = "SELECT `uid` FROM `".\Config\Sys::$dbprefix."agentlinks` WHERE `id`=".$paras['lid']." LIMIT 1";
            $links = $db->row($sql);
            if($links['uid'] == $user['uid']) {
                $minrebatevalue = $utility->getSystemParams('minrebatevalue');
                $maxrebatevalue = (floatval($user['rebate']) - floatval($minrebatevalue));

                if($maxrebatevalue >= $paras['rebate']) {
                    $sql = "UPDATE `" . \Config\Sys::$dbprefix . "agentlinks` SET `rebate`=" . $paras['rebate'] . " WHERE `id`=" . $paras['lid'] . " LIMIT 1";
                    $db->query($sql);
                    $result = array(
                        'state' => 200,
                        'msgid' => 200,
                        'msg' => '返点设置为'.$paras['rebate'].'%，成功',
                    );
                }else{
                    $result = array(
                        'state' => 404,
                        'msgid' => 404,
                        'msg' => '返点设置错误，须在 0% - '.$maxrebatevalue.'%之间',
                    );
                }
            }else{
                $result = array(
                    'state' => 404,
                    'msgid' => 404,
                    'msg' => $user['uid'].'推广链接所属不明，返点设置失败'.$links['uid'],
                );
            }
        }
        return $result;
    }
    public static function agentLinksDelete($args){
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            "cmd",
            "token",
            "lid|N",
        );
        $paras = $utility->get_url_args($args, $url_args);

        $result = array(
            'state'=>404,
            'msgid'=>404,
            'cmd'=>$paras['cmd']
        );

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if ($user['state'] == 200) {
            $sql = "SELECT `uid` FROM `".\Config\Sys::$dbprefix."agentlinks` WHERE `id`=".$paras['lid']." LIMIT 1";
            $links = $db->row($sql);
            if($links['uid'] == $user['uid']) {
                $sql = "DELETE FROM `" . \Config\Sys::$dbprefix . "agentlinks` WHERE `id`=" . $paras['lid'] . " LIMIT 1";
                $db->query($sql);
                $result = array(
                    'state' => 200,
                    'msgid' => 200,
                    'msg' => '推广链接删除成功',
                );
            }else{
                $result = array(
                    'state' => 404,
                    'msgid' => 404,
                    'msg' => '推广链接所属不明，操作失败',
                );
            }
        }
        return $result;
    }
    public static function agentLinksList($args){
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            "cmd",
            "token",
            "usertype|N",
        );
        $paras = $utility->get_url_args($args, $url_args);

        $result = array(
            'state'=>404,
            'msgid'=>404,
            'cmd'=>$paras['cmd']
        );

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if ($user['state'] == 200) {
            $sql = "SELECT `id`,`rebate`,`numbers`,`state`,`usertype` FROM `".\Config\Sys::$dbprefix."agentlinks` WHERE `uid`=".$user['uid'];
            $links = $db->query($sql);
            $result = array(
                'state' => 200,
                'datas' => $links,
            );
        }
        return $result;
    }
    # endregion

    # region 用户注册
    public static function registerUser($args){
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            "cmd",
            "password",
            'nickname',
            'rebate|F',
            'repassword',
            'usertype|N',
            'parentuno',
            'lid|N',
            'tel',
            'codeError',
            'verify',
            'codemobile',
            'remoteip',
            'client_type|N',
            'browser',
            'os',
        );
        $paras = $utility->get_url_args($args, $url_args);
        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);

        $enabletryregister = intval($utility->getSystemParams('enabletryregister'));
        if($paras['usertype']==0 && $enabletryregister == 0){
            $result['msgid'] = 10104;//暂时不提供试玩帐号注册，请注册正式帐号;
            return $result;
        }
        if(empty($paras['tel']))
        {
            $result['msgid'] = 10061;//手机号码无效;
            return $result;
        }
        if(!empty($paras['tel']) && !$utility->isMobileNumber($paras['tel']))
        {
            $result['msgid'] = 10061;//手机号码无效;
            return $result;
        }
        if(empty($paras['nickname'])){
            $result['msgid'] = 10009;//'用户名不能为空';
            return $result;
        }
        if(empty($paras['password'])){
            $result['msgid'] = 10010;//'登录密码不能为空';
            return $result;
        }
        if($paras['password'] != $paras['repassword']){
            $result['msgid'] = 10011;//'两次密码输入不一致';
            return $result;
        }

        if(empty($paras['remoteip']) || $paras['remoteip']=='2147483647'){
            $result['msgid'] = 10006;
            $result['ip'] = $paras['remoteip'];
            return $result;
        }

//        if($paras['codeError'] >= 4 && empty($paras['verify'])){
//            $result['msgid'] = 10088;
//            return $result;
//        }
//        if($paras['codeError'] < 4 && $paras['verify']!='123') {
//            # 验证码是否正确
//            $verify = $utility->redisGet('verify_' . md5($paras['verify']));
//            if (!$verify && $verify != $paras['verify']) {
//                $result['msgid'] = 10088;
//                return $result;
//            }
//        }

        # 如果开启了注册手机验证
        $mastsmsverify = intval($utility->getSystemParams('enableregsms'));
        if($mastsmsverify){
            $redis_verify = $utility->redisGet('sms_'.$paras['tel']);
            if(!$redis_verify){
                $result['msgid'] = 10112; // 验证码无效
                return $result;
            }
            if(empty($paras['codemobile'])){
                $result['msgid'] = 10112; // 验证码无效
                return $result;
            }
            if($paras['codemobile'] != $redis_verify){
                $result['msgid'] = 10112; // 验证码无效
                return $result;
            }
        }

        # 统计当前IP今天共注册了几个帐号
        $ips = $db->row("SELECT regip,COUNT(uid) as _TOTAL FROM `rp_users` WHERE `regip`=".$paras['remoteip']);
        $ipmax = intval($utility->getSystemParams('ipmax'));
        $ips['remoteip'] = $paras['remoteip'];

        if($ipmax > 0 && intval($ips['_TOTAL']) > $ipmax ){
            $result['msgid'] = 10108;//同一地址注册的帐号已超过限制
            return $result;
        }

        //检测手机号码是否已被注册
        $user = $db->row("SELECT `uid` AS _TOTAL FROM `rp_users` WHERE `tel`='{$paras['tel']}' AND `usertype`>0");
        if($user){
            $result['msgid'] = 10062;//'手机号码已绑定在其它玩家帐号';
            return $result;
        }

        //生成密码token
        $token = $utility->randString(4);
        $makePasswd = $utility->encrypt($paras['password'],'E',$token);

        if(!empty($paras['lid'])){
            $sql = "SELECT u.`uno`,l.`rebate`, l.`usertype` FROM `".Config\Sys::$dbprefix."agentlinks` l, `rp_users` u WHERE u.`uid`=l.`uid` AND `id`=".$paras['lid']." LIMIT 1";
            $link = $db->row($sql);
            $paras['parentuno'] = $link['uno'];
            $paras['rebate'] = $link['rebate'];
            $paras['usertype'] = $link['usertype'];
            # 更新推广链接的注册人数
            $sql = "UPDATE `".Config\Sys::$dbprefix."agentlinks` SET `numbers`=`numbers`+1 WHERE `id`=".$paras['lid']." LIMIT 1";
            $db->query($sql);
        }

        # 如果邀请人不能为空，注册时没有填写邀请人
        $mastparent = intval($utility->getSystemParams('mastparent'));
        if(empty($paras['parentuno']) && $mastparent == 1){
            $result['msgid'] = 10080; //没有填写邀请人
            return $result;
        }

        $parent = false;
        if(!empty($paras['parentuno'])) {
            $parentSql = "SELECT `uid`,`uno`,`coin`,`score`,`parentid`,`parents`,`tel`,`agentlevel`,`userlevel`,`rebate` FROM `" . \Config\Sys::$dbprefix . "users` WHERE `uno`='" . $paras['parentuno'] . "' OR `tel`='" . $paras['parentuno'] . "' AND `usertype`>0 LIMIT 1";
            $parent = $db->row($parentSql);
            if (!$parent) {
                $result['msgid'] = 10039;// 邀请人的帐号不存在;
                return $result;
            }

        }

        # 检测返点值是否大于上级的最大返点值
        if($parent) {
            $minrebatevalue = $utility->getSystemParams('minrebatevalue');
            if (floatval($paras['rebate']) > (floatval($parent['rebate']) - floatval($minrebatevalue))) {
                $result['msgid'] = 10114;// 返点值不正确;
                return $result;
            }
        }

        //生成唯一编码（像QQ号一样的）
        $uno = '';
        while (empty($uno)) {
            $uno = $utility->makeUserNo();
        }

        $webtoken = $utility->settoken($uno, $token);

        # 随机头像
        $roundAvatar = $utility->roundAvatarList();
        $userAvatar = array_rand($roundAvatar);
        $insert_data = array(
            'uno' => $uno,
            'nickname'=>$paras['nickname'],
            'passwd'=>$makePasswd,
            'tel'=>$paras['tel'],
            'regtimes'=>time(),
            'regip'=>$paras['remoteip'],
            'rebate'=>$paras['rebate'],
            'usertype'=>$paras['usertype'],
            'lastlogintimes'=>time(),
            'token'=>$token,
            'webtoken'=>$webtoken,
            'avatar' => $roundAvatar[$userAvatar]['imgurl'],
            'parentid' => 0,
        );

        $agent_pushusergive = 0;
        # 找出玩家的邀请人
        if($parent) {
            if (trim($parent['tel']) != trim($paras['tel'])) {
                # 更新邀请人
                /*
                $parent_cols = array(
                    'parentid' => $parent['uid'],
                    'parents' => $parent['parents'] . ',' . $parent['uid'],
                );
                $db->update(\Config\Sys::$dbprefix . 'users')->cols($parent_cols)->where('uid=' . $uid)->query();
                */
                $insert_data['parentid'] = $parent['uid'];
                $insert_data['parents'] = $parent['parents'] . ',' . $parent['uid'];
            }
        }

        if(!$insert_data['parentid'] && $mastparent == 1){
            $result['msgid'] = 10039;// 邀请人的帐号不存在;
            return $result;
        }
        try{
            $db->beginTrans();
            $uid = $db->insert(\Config\Sys::$dbprefix.'users')->cols($insert_data)->query();

            if(!$uid){
                return array(
                    'state' => 404,
                    'cmd' => $paras['cmd'],
                    'msgid' => 10006,
                );
            }
            # 加入注册登录日志中
            $session = array(
                'uid' => $uid,
                'logintime' => time(),
                'accesstime' => time(),
                'loginip' => $paras['remoteip'],
                'client_type' => $paras['client_type'],
                'browser' => $paras['browser'],
                'os' => $paras['os'],
            );
            $db->insert(\Config\Sys::$dbprefix.'users_session')->cols($session)->query();
            # 自动进入概率库
            $autoinprobability = intval($utility->getSystemParams('autoinprobability'));
            if($autoinprobability)
            {
                $defaultprobability = floatval($utility->getSystemParams('defaultprobability'));
                $db->insert(\Config\Sys::$dbprefix.'users_probability')->cols(array(
                    'uid' => $uid,
                    'winpoints' => $defaultprobability,
                    'jointime' => time(),
                    'effectivetime' => intval($utility->getSystemParams('probabilitytimes')),
                ))->query();
            }
            # 注册赠送
            $registergive = ($paras['usertype'] ? $utility->getSystemParams('registergive') : $utility->getSystemParams('registertrygive'));
            $usercoin = floatval($registergive);
            if($usercoin > 0){
                $giveParams = array(
                    'uid'       => $uid,
                    'amount'    => $usercoin,
                    'usertype'  => $paras['usertype'],
                    'usercoin'  => 0,
                    'nowtime'   => time(),
                    'transfername' => '',
                    'info'      => '注册赠送'
                );
                $payline = array(
                    'bankid' => 24,
                    'paywayid'  => 1,
                    'id'     => 1,
                );
                $rechargeid = $utility->neworderno();
                $recharge_log = array(
                    'uid' => $giveParams['uid'],
                    'usertype' => $giveParams['usertype'],
                    'rechargeid' => $rechargeid,
                    'amount' => $giveParams['amount'],
                    'coin' => $giveParams['usercoin'],
                    'bankid' => $payline['bankid'],
                    'paywayid' => $payline['paywayid'],
                    'lineid' => $payline['id'],
                    'actiontime' => $giveParams['nowtime'],
                    'transfername' => $giveParams['transfername'],
                    'info' => '注册赠送',
                    'rechargeamount'    => $giveParams['amount'],
                    'rechargetime'    => $giveParams['nowtime'],
                    'state' => 1
                );
                $db->insert(\Config\Sys::$dbprefix.'users_recharge')->cols($recharge_log)->query();
                $utility->setCoin(
                    array(
                        'uid' => $uid,
                        'coin' => floatval($usercoin),
                        'gameid' => 0,
                        'liqtype' => 23, //赢家，退回对应预投注的红包
                        'ex1' => 0,
                        'ex2' => '',
                    )
                );
            }
            $givescore = $utility->getSystemParams('reggivescore');
            if(floatval($givescore)>0){
                $utility->setScore(
                    array(
                        'uid' => $uid,
                        'score' => floatval($givescore),
                        'gameid' => 0,
                        'liqtype' => 4,
                    )
                );
            }

            $db->commitTrans();
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'users' => array(
                    'uid' => $uid,
                    'uno' => $uno,
                    'nickname' => $paras['nickname'],
                    'avatar' => $roundAvatar[$userAvatar]['imgurl'],
                    'token'=>$webtoken,
                    'usertype'=>$paras['usertype'],
                ),
                'coin_liqtype' => \Config\Sys::$liqtype,
                'score_liqtype' => \Config\Sys::$scoreliqtype,
                'sys' => $utility->getForClientParams(),
                'pushusergive' => $agent_pushusergive,
            );
            return $result;
        }catch (PDOException $e){
            $db->rollBackTrans();
            $result = [
                'state' => $e->getCode(),
                'msg'   => $e->getMessage(),
                'data'  => []
            ];
            return $result;
        }



        # 注册成功返回数据
        /*
        $result = array(
            'state' => 200,
            'cmd' => $paras['cmd'],
            'users' => array(
                'uid' => $uid,
                'uno' => $uno,
                'tel' => substr($insert_data['tel'],0,3).'****'.substr($insert_data['tel'],-1,4),
                'qq' => '',
                'wx' => '',
                'coin' => $usercoin,
                'score' => $givescore,
                'username' => '',
                'nickname' => $paras['nickname'],
                'avatar' => 'avatar/no.png',
                'lastlogintimes'=>$insert_data['lastlogintimes'],
                'token'=>$webtoken,
                'usertype'=>$paras['usertype'],
            ),
            'coin_liqtype' => \Config\Sys::$liqtype,
            'score_liqtype' => \Config\Sys::$scoreliqtype,
            'sys' => $utility->getForClientParams(),
            'pushusergive' => $agent_pushusergive,
        );
        */

    }
    # endregion

    # region 用户登录
    public static function userLogin($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'remoteip',
            'un',
            'pw',
            'vc',
            'codeError|N',
            'client_type|N',
            'browser',
            'os',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $sysMt = $utility->systemSystemMaintenance($paras['cmd']);
        if($sysMt['state'] != 200){
            return $sysMt;
        }

        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);

        if(empty($paras['un']) || empty($paras['pw'])){
            return $result;
        }
//        if($paras['codeError'] >= 4 && empty($paras['vc'])){
//            $result['msgid'] = 10088;
//            return $result;
//        }
//        if($paras['codeError'] < 4 && $paras['vc']!='123') {
//            # 验证码是否正确
//            $verify = $utility->redisGet('verify_' . md5($paras['vc']));
//            if (!$verify && $verify != $paras['vc']) {
//                $result['msgid'] = 10088;
//                return $result;
//            }
//        }

        //查询用户是否存在 - 当一个手机号码注册了试玩和正式时，用手机号码登录将取最后一个注册的帐号，其它只能用玩家号码登录
        $fields = "`uid`,`uno`,`username`,`nickname`,`passwd`,`lastlogintimes`,`usertype`,`token`,`webtoken`,`coin`,`avatar`,`tel`,`qq`,`wx`,`isdelete`";
        $tablename = '`'.\Config\Sys::$dbprefix.'users`';
        $sql = "SELECT {$fields} FROM {$tablename} WHERE (`uno`='{$paras['un']}' OR `tel`='{$paras['un']}' OR `username`='{$paras['un']}') ORDER BY `uid` DESC LIMIT 1";
        $user = $db->row($sql); //$this->db->query($sql);
        $makePasswd = $utility->encrypt($paras['pw'],'E',$user['token']);
        if(!$user){
            $result['msgid'] = 10003;//帐号不存在
            return $result;
        }else{
            if($user['isdelete']){
                $result['msgid'] = 10002;
                return $result;
            }
            if($user['passwd'] != $makePasswd){
                $result['msgid'] = 10004;//帐号密码不正确
                return $result;
            }else{
                //生成密码token
                $webtoken = $utility->settoken($user['uno'], $user['token']);
                //保存token
                $db->update(\Config\Sys::$dbprefix.'users')->cols(
                    array(
                        'lastip' => $paras['remoteip'],
                        'webtoken'=>$webtoken,
                        'lastlogintimes'=>time()
                    )
                )->where('`uid`='.$user['uid'])->query();
                $user['usercoin'] = $user['coin'];
                //unset($user['uid']);
                unset($user['passwd']);
                unset($user['token']);
                unset($user['webtoken']);
                unset($user['cmd']);
                unset($user['state']);
                unset($user['coin']);
                unset($user['isdelete']);

                $user['token'] = $webtoken;

                # 加入注册登录日志中
                $session = array(
                    'uid' => $user['uid'],
                    'logintime' => time(),
                    'accesstime' => time(),
                    'loginip' => $paras['remoteip'],
                    'client_type' => $paras['client_type'],
                    'browser' => $paras['browser'],
                    'os' => $paras['os'],
                );
                $db->insert(\Config\Sys::$dbprefix.'users_session')->cols($session)->query();

                $result = array(
                    'state' => 200,
                    'cmd' => $paras['cmd'],
                    'coin_liqtype' => \Config\Sys::$liqtype,
                    'score_liqtype' => \Config\Sys::$scoreliqtype,
                    'sys' => $utility->getForClientParams(),
                    'users' => $user,
                );
                return $result;
            }
        }
        //Gateway::sendToCurrentClient(json_encode($result));
        //Gateway::closeClient($client_id);

    }
    # endregion

    # region 用户是否登录
    public static function checkUserLoged($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'isclose|S|true',
            'pw',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if ($user['state'] == 200) {
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'currencyName' => $utility->getSystemParams('currencyName'),
                'nickname' => $user['nickname'],
                'usercoin' => $user['usercoin'],
                'userscore' => $user['userscore'],
                'isclose' => $paras['isclose'],
                'uno' => $user['uno'],
                'uid' => $user['uid'],
                'token' => $paras['token'],
            );
        } else {
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'usercoin' => 0,
                'msgid' => $user['msgid'],
                'isclose' => $paras['isclose'],
            );
        }
        return $result;
    }
    # endregion

    # region 按token拉取用户信息
    public static function getUserInfoForToken($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if($user['state']==200){
            //unset($user['uid']);
            unset($user['cmd']);
            unset($user['state']);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'users' => $user,
                //'marquee' => $utility->getMarquees(array('cmd'=>'marquee')), // 出错了
                'online' => $utility->getUserOnline(),
            );
            # 用户短信统计
            $mailtotal = $utility->getUserMailCount($user['uid']);
            $result['mailtotal'] = intval($mailtotal);
            # 计算用户离下个VIP升级的相关数据
            $result['updatelevel'] = $utility->userNextUpdateLevel($user['uid'], $user['userlevel'],$user['recharge'],$user['betcoin']);
            # 积分功能开启标识
            $result['enablescore'] = intval($utility->getSystemParams('enablescore'));
            # 传红包功能开启标识
            $result['enablechange'] = intval($utility->getSystemParams('enablechange'));
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
                //'marquee' => $utility->getMarquees(array('cmd'=>'marquee')),
                'online' => $utility->getUserOnline(),
            );
        }
        return $result;
    }
    # endregion

    # region 按token拉取用户的余额
    public static function getUserCoin($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'], $paras['cmd']);

        /* 各种游戏的当前红包数 */

        # 数据缓存1秒
        $gameCount = $utility->redisGet(\Config\Sys::$redisKey['GCOUNT']);
        if(!$gameCount) {
            $where_txt = "(l.`overtime` - (UNIX_TIMESTAMP() - l.`begintimes`)) > 0 AND l.`state`=0";
            # 统计当前房间的红包及在线人数
            $sql = "SELECT g.id,IFNULL(count1,0) AS count FROM `" . \Config\Sys::$dbprefix . "games` g LEFT JOIN (SELECT l.gameid,COUNT(1) AS count1 FROM `" . \Config\Sys::$dbprefix . "bets` l WHERE " . $where_txt . " GROUP BY l.`gameid`) t1 ON t1.gameid=g.id";
            $gameCount = $db->query($sql);
            $utility->redisSetEx(\Config\Sys::$redisKey['GCOUNT'], $gameCount, 3);
        }

        $onlinecount = $utility->getSystemParams('onlinecount');

        # 随机加减
        $rand = 0;
        $onlinecount = $onlinecount + $rand;

        if($user['state']==200){
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'uc' => $utility->formatCoin($user['usercoin']), // 帐户余额
                'us' => intval($user['userscore']), // 积分总额
                'bt' => $utility->formatCoin($user['backtotal']), // 返水总额
                'gc' => $gameCount,
                'online' => $onlinecount,
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
                'gc' => $gameCount,
                'online' => $onlinecount,
            );
        }

        return $result;
    }
    # endregion

    # region 发包日志查询
    public static function sendRedEnvelopesLog($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        # "ps","pc",'begintimes','endtimes','state','gameid'
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'pc|N|1',
            'ps',
            'begintimes',
            'endtimes',
            'state',
            'gameid',
            'issue',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;

            $where_txt = " AND b.`uid`={$user['uid']}";

            if(isset($paras['state']) && $paras['state']!='') $where_txt .= ' AND b.`state`='.intval($paras['state']);
            if(isset($paras['gameid']) && $paras['gameid']!='') $where_txt .= ' AND b.`gameid`='.intval($paras['gameid']);
            if(isset($paras['issue']) && $paras['issue']!='') $where_txt .= ' AND b.`issue`='.intval($paras['issue']);

            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND b.`begintimes` > ' . $begintimes . ' AND b.`begintimes` < ' . $endtimes;

            $tablename = "`".\Config\Sys::$dbprefix."bets` b,`".\Config\Sys::$dbprefix."games` g";
            $sql = "SELECT ~field~ FROM {$tablename} WHERE g.`id`=b.`gameid` {$where_txt} ~order~ ~limit~";
            //取出当前页的数据
            $sql_arr = array(
                'field' => "b.`issue`,b.`gameid`,g.`title`,b.`uid`,b.`need`,b.`cur`,b.`coin`,FROM_UNIXTIME(b.`begintimes`) AS sendtimes,b.`state`,b.`usedtimes`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY `begintimes` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => $datas['total'],
                'curpage' => $paras['pc'],
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 抢包日志查询
    public static function grabRedEnvelopesLog($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        # "ps","pc",'begintimes','endtimes','state','gameid'
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'pc|N|1',
            'ps',
            'begintimes',
            'endtimes',
            'state',
            'gameid',
            'issue',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );
        if($user['state']==200) {
            $uid = $user['uid'];
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;

            $where_txt = " AND b.`uid`={$uid}";

            if(isset($paras['state']) && $paras['state']!='') $where_txt .= ' AND b.`state`='.intval($paras['state']);
            if(isset($paras['gameid']) && $paras['gameid']!='') $where_txt .= ' AND b.`gameid`='.intval($paras['gameid']);
            if(isset($paras['issue']) && $paras['issue']!='') $where_txt .= ' AND b.`issue`='.intval($paras['issue']);

            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND b.`times` > ' . $begintimes . ' AND b.`times` < ' . $endtimes;

            $sql = "SELECT ~field~ FROM `".\Config\Sys::$dbprefix."betslog` b,`".\Config\Sys::$dbprefix."games` g WHERE g.`id`=b.`gameid` AND 1 {$where_txt} ~order~ ~limit~";
            //取出当前页的数据
            $sql_arr = array(
                'field' => "b.`issue`,b.`gameid`,g.`title`,b.`cardtype`,b.`betcoin`,(SELECT o.`cardtitle` FROM `".\Config\Sys::$dbprefix."games_odds` o WHERE o.`cardtype` = b.`cardtype` AND b.`odds`=o.`odds` AND o.`gameid` = b.`gameid` LIMIT 1) AS cardtitle,b.`ticket`,b.`winerprofit`,b.`profit`,b.`uid`,b.`coin`,FROM_UNIXTIME(b.`times`) AS sendtimes,b.`state`,b.`usedtimes`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY `times` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => $datas['total'],
                'curpage' => $paras['pc'],
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion
    #创建房间记录
    public static function createroomEnvelopesLog($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        # "ps","pc",'state','gameid'
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'pc|N|1',
            'ps',
            'begintimes',
            'endtimes',
            'state',
            'gameid',
        );
        $paras = $utility->get_url_args($paras, $url_args);
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );
        if($user['state']==200) {
            $uid = $user['uid'];
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;
            $where_txt = " AND r.`uid`={$uid}";
            if(isset($paras['state']) && $paras['state']!='')
                $where_txt .= ' AND r.`status`='.intval($paras['state']);
            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND r.`createtimes` > ' . $begintimes . ' AND r.`createtimes` < ' . $endtimes;

            $sql = "SELECT ~field~ FROM `".\Config\Sys::$dbprefix."rooms_game` r,`".\Config\Sys::$dbprefix."games` g WHERE g.`id`=r.`game_id` AND 1 {$where_txt} ~order~ ~limit~";
            $sql_arr = array(
                'field' => "r.*,g.`title`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY `createtimes` DESC',
            );

            $datas = $utility->getTableRows($sql, $sql_arr);
            foreach ( $datas['datas'] as $k=>$v ){
                $datas['datas'][$k]['room_num'] = date('Ymd',$v['createtimes']).'-'.$v['id'];
                $datas['datas'][$k]['createtimes'] = date('Y-m-d H:i:s',$v['createtimes']);
                $datas['datas'][$k]['endtimes'] = date('Y-m-d H:i:s',$v['endtimes']);
            }
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => $datas['total'],
                'curpage' => $paras['pc'],
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );

        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }

    # endregion

    # region 传包日志查询
    public static function transferLog($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'pc|N|1',
            'ps',
            'remoteip',
            'begintimes',
            'endtimes',
            'touno',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );
        if($user['state']==200) {
            //需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps'];

            $where_txt = " AND u.`uid`=l.`touid`";

            if(isset($paras['state']) && $paras['state']!='') $where_txt .= ' AND l.`state`='.intval($paras['state']);
            if(isset($paras['touno']) && !empty($paras['touno'])) $where_txt .= " AND l.`touno`='{$paras['touno']}'";

            $where_txt .= ' AND l.`fromuid`='.$user['uid'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;
            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`times` > ' . $begintimes . ' AND l.`times` < ' . $endtimes;
            $tablename = "`".\Config\Sys::$dbprefix."transfer_log` l,`".\Config\Sys::$dbprefix."users` u";
            $sql = "SELECT ~field~ FROM {$tablename} WHERE 1 {$where_txt} ~order~ ~limit~";
            //取出当前页的数据
            $sql_arr = array(
                'field' => "u.`uno`,u.`nickname`,u.`avatar`,l.`id`,l.`touid`,l.`fromuid`,l.`coin`,l.`rate`,FROM_UNIXTIME(l.`times`) AS times,l.`state`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY l.`times` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => $datas['total'],
                'curpage' => $paras['pc'],
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 收包日志查询
    public static function transferToMeLog($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'pc|N|1',
            'ps',
            'remoteip',
            'begintimes',
            'endtimes',
            'fromuno'
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );
        if($user['state']==200) {
            //需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps'];

            $where_txt = " AND u.`uid`=l.`fromuid`";

            if(isset($paras['state']) && $paras['state']!='') $where_txt .= ' AND l.`state`='.intval($paras['state']);
            if(isset($paras['fromuno']) && !empty($paras['fromuno'])) $where_txt .= " AND l.`fromuno`='{$paras['fromuno']}'";

            $where_txt .= ' AND l.`touid`='.$user['uid'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;
            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`times` > ' . $begintimes . ' AND l.`times` < ' . $endtimes;
            $tablename = "`".\Config\Sys::$dbprefix."transfer_log` l,`".\Config\Sys::$dbprefix."users` u";
            $sql = "SELECT ~field~ FROM {$tablename} WHERE 1 {$where_txt} ~order~ ~limit~";
            //取出当前页的数据
            $sql_arr = array(
                'field' => "u.`uno`,u.`nickname`,u.`avatar`,l.`id`,l.`touid`,l.`fromuid`,l.`coin`,l.`rate`,FROM_UNIXTIME(l.`times`) AS times,l.`state`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY l.`times` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => $datas['total'],
                'curpage' => $paras['pc'],
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 单期红包数据
    public static function RedEnvelopesForIssueItem($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'issue',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 10020,
        );
        if(empty($paras['issue'])){
            return $result;
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            $grabusers = $utility->getGameForIssueIsEnd($paras['issue']);
            if(count($grabusers["datas"])==0)
            {
                $result['msgid'] = 10038; // 红包未抢完或超时，无详情可查阅
                return $result;
            }
            # 格式化显示数据
            foreach ($grabusers['grabusers'] as $k=>$v){
                $grabusers['grabusers'][$k]['times'] = $utility->formatTimes($grabusers['grabusers'][$k]['times']);
                switch ($v['cardtitle'])
                {
                    case '2倍':
                    case '1.5倍':
                    case '1倍':
                    case '比大小':
                        $grabusers['grabusers'][$k]['cardtitle'] = '';
                        break;
                    default:
                        break;
                }
            }
            $result = array(
                'state' => 200,
                'issue' => $paras['issue'],
                'times' => $utility->formatTimes($grabusers['datas']['begintimes']),
                'ecost' => '',
                'ecoin' => '',
                'gameid' => $grabusers['datas']['gameid'],
                'betcoin' => $utility->formatCoin($grabusers['datas']['coin']),
                'mantissa' => $grabusers['datas']['mantissa'],
                'datas' => $grabusers['datas'],
                'grabusers' => $grabusers['grabusers'],
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 资金帐变日志
    public static function userCoinLog($paras)
    {
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'liqtype',
            'issue',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );

        if($user['state']==200){
            # 需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);

            $where_txt = "l.`uid`=".$user['uid'];
            if(!empty($paras['liqtype'])) $where_txt .= " AND l.`liqtype`=".$paras['liqtype'];
            if(!empty($paras['issue'])) $where_txt .= " AND l.`ex2`=".$paras['issue'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;
            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`times` > ' . $begintimes . ' AND l.`times` < ' . $endtimes;
            $db_ym = date('Ym', $begintimes);
            $tablename = \Config\Sys::$dbprefix.'coinlog_'.$db_ym.' l';

            $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";
            # 取出当前页的数据字段、当前页、每页显示数、排序
            $sql_arr = array(
                'field' => "l.`id`,l.`gameid`,l.`coin`,l.`usercoin`,l.`liqtype`,FROM_UNIXTIME(l.`times`) AS actiontimes,l.`ex1`,l.`ex2`,l.`ex3`,(SELECT g.`title` FROM `".\Config\Sys::$dbprefix."games` g WHERE g.`id`=l.`gameid`) as gamename",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY `id` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => intval($datas['total']),
                'curpage' => intval($paras['pc']),
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 积分帐变日志
    public static function userScoreLog($paras)
    {
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'liqtype',
            'issue',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );

        if($user['state']==200){
            # 需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);

            $where_txt = "l.`uid`=".$user['uid'];
            if(!empty($paras['liqtype'])) $where_txt .= " AND l.`liqtype`=".$paras['liqtype'];
            if(!empty($paras['issue'])) $where_txt .= " AND l.`issue`=".$paras['issue'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;
            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`times` > ' . $begintimes . ' AND l.`times` < ' . $endtimes;
            $tablename = \Config\Sys::$dbprefix.'scorelog l';

            $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";
            # 取出当前页的数据字段、当前页、每页显示数、排序
            $sql_arr = array(
                'field' => "l.`id`,l.`gameid`,l.`score`,l.`userscore`,l.`liqtype`,FROM_UNIXTIME(l.`times`) AS actiontimes,l.`ex1`,l.`ex2`,l.`ex3`,(SELECT g.`title` FROM `".\Config\Sys::$dbprefix."games` g WHERE g.`id`=l.`gameid`) as gamename",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY `id` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => intval($datas['total']),
                'curpage' => intval($paras['pc']),
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 兑换订单
    public static function exchangeOrdersLog($paras)
    {
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'state',
            'orderid',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        //print_r($paras);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );

        if($user['state']==200){
            # 需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);

            $where_txt = "l.`uid`=".$user['uid']." AND l.`proid`=p.`code`";

            if(!empty($paras['state'])) $where_txt .= " AND l.`state`=".$paras['state'];
            if(!empty($paras['orderid'])) $where_txt .= " AND l.`orderid`='".$paras['orderid']."'";

            $begintimes = $user['regtimes'];//strtotime(date('Y-m-d'));
            $endtimes = strtotime(date('Y-m-d')) + 86400;
            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`actiontime` > ' . $begintimes . ' AND l.`actiontime` < ' . $endtimes;
            $tablename = \Config\Sys::$dbprefix.'exchange_orders l,'.\Config\Sys::$dbprefix.'products p';

            $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";
            # 取出当前页的数据字段、当前页、每页显示数、排序
            $sql_arr = array(
                'field' => "l.`id`,l.`orderid`,l.`price`,l.`numbers`,l.`amount`,l.`scoreamount`,l.`state`,FROM_UNIXTIME(l.`actiontime`) AS actiontime,l.`consignee`,l.`address`,l.`tel`,l.`expressltd`,l.`expressnumber`,l.`remarks`,p.`title`,p.`price`,p.`pricenet`,REPLACE(p.`icon1`,'/upload/','') as icon,`paytype`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY `actiontime` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => $datas['total'],
                'curpage' => $paras['pc'],
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 充值记录
    public static function userRechargeLog($paras)
    {
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'orderid',
            'state',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );

        if($user['state']==200){
            # 需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);

            $where_txt = "l.`uid`=".$user['uid'];
            if(!empty($paras['orderid'])) $where_txt .= " AND l.`rechargeid`='".$paras['orderid']."'";
            if($paras['state']!='') $where_txt .= " AND l.`state`=".$paras['state'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;

            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`actiontime` > ' . $begintimes . ' AND l.`actiontime` < ' . $endtimes;
            $tablename = \Config\Sys::$dbprefix.'users_recharge l';

            $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";
            # 取出当前页的数据字段、当前页、每页显示数、排序
            $sql_arr = array(
                'field' => "l.`rechargeid`,l.`amount`,l.`rechargeamount`,l.`coin`,l.`info`,FROM_UNIXTIME(l.`actiontime`) AS actiontimes,l.`state`,l.`bankid`",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY l.`id` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => intval($datas['total']),
                'curpage' => intval($paras['pc']),
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region  确认银行转帐 - 当用户点击已完成存款后的更新
    public static function confirmRechargeTransfer($paras){
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'rechargeid', // 充值订单号
            'transfername' // 充值的姓名
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            # 找出单前的充值订单号
            $sql = "SELECT `paywayid` FROM `".\Config\Sys::$dbprefix."users_recharge` WHERE `recharegeid`='".$paras['rechargeid']."' AND `state`=0 AND `transferstate`=0 LIMIT 1";
            $tr = $db->row($sql);
            if(!$tr){
                return array(
                    'state' => 404,
                    'msgid' => 10000, // 数据查询失败
                );
            }
            if(intval($tr['paywayid']) != 2){
                return array(
                    'state' => 404,
                    'msgid' => 10000, // 数据查询失败，线路不正确 - 不是银行转帐
                );
            }

            try {
                $db->beginTrans();

                $sql = "UPDATE `" . \Config\Sys::$dbprefix . "users_recharge` SET `transferstate`=1 WHERE `recharegeid`='" . $paras['rechargeid'] . "' AND `state`=0 AND `transferstate`=0 LIMIT 1";
                $db->query($sql);

                $db->commitTrans();
            }catch (PDOException $e){
                $db->rollBackTrans(); // 执行失败，事务回滚
            }

            $result = array(
                'state' => 200,
                'msgid' => 10079, // 存款成功
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 提现记录
    public static function userCashLog($paras)
    {
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'orderid',
            'state',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        $result = array(
            'state' => 404,
            'cmd' => $paras['cmd'],
            'msgid' => 404,
        );

        if($user['state']==200){
            # 需要处理的页面参数，用来翻页操作
            $page_args = $utility->get_page_args($paras, $url_args);

            $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);

            $where_txt = "l.`uid`=".$user['uid']." AND b.id=l.bankid AND bl.id=b.bankid";
            if(!empty($paras['orderid'])) $where_txt .= " AND l.`cashid`='".$paras['orderid']."'";
            if($paras['state']!='') $where_txt .= " AND l.`state`=".$paras['state'];

            $begintimes = strtotime(date('Y-m-d'));
            $endtimes = $begintimes + 86400;

            if(!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
            if(!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;
            $where_txt .= ' AND l.`cashtime` > ' . $begintimes . ' AND l.`cashtime` < ' . $endtimes;
            $tablename = \Config\Sys::$dbprefix.'users_cash l,'.\Config\Sys::$dbprefix.'users_bank b,'.\Config\Sys::$dbprefix.'bank_list bl';

            $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";
            # 取出当前页的数据字段、当前页、每页显示数、排序
            $sql_arr = array(
                'field' => "l.`cashid`,l.`amount`,l.`coin`,l.`info`,FROM_UNIXTIME(l.`cashtime`) AS actiontimes,l.`state`,bl.`title`,b.`name`,right(b.`account`,4) AS account",
                'page_current' => $paras['pc'],
                'pagesize' => $_pagesize,
                'order' => ' ORDER BY l.`id` DESC',
            );
            $datas = $utility->getTableRows($sql, $sql_arr);
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => $datas['datas'],
                'record' => intval($datas['total']),
                'curpage' => intval($paras['pc']),
                'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
                'urlparas' => http_build_query($page_args),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion

    # region 玩家数据统计
    public static function statisticsAgentForUid($uid, $searchTime = 0)
    {
        global $db;
        global $utility;

        $functionRunBeginTimes = microtime(true);

        if(empty($searchTime)) $searchTime = time();
        $TWL = $utility->getTWLTimes($searchTime);

        # 统计的数据如果不是今天的要将数据保存到数据表，以后查询直接取数
        # 统计今天的数据库直接以下过程
        $searchDate = date("Y-m-d", $searchTime);
        $todayDate = date("Y-m-d", time());

        $redis_key = \Config\Sys::$redisKey['PROFIT'] . $uid . '_' . $searchDate;

        # 如果查询的不是当天的，如果表中没有记录即要入库
        $isToday = (($searchDate == $todayDate) ? true : false);

        $sql = "SELECT `uid`,`actiontimes`,`jsonvalue` FROM `".\Config\Sys::$dbprefix."st` WHERE `uid`=".$uid." AND `actiontimes`=".$TWL['todayBegin']." LIMIT 1";
        $searchData = $db->row($sql);

        $searchData = false;

        if(!$searchData) {
            $data = $utility->redisGet($redis_key);
            if (!$data) {
                $db_prefix = \Config\Sys::$dbprefix;
                # 找出当前玩家
                $sql = 'SELECT `uno`,`userlevel`,`betcoin`,`recharge`,`profit`,`coin` FROM `' . $db_prefix . 'users` WHERE `uid`=' . $uid . ' LIMIT 1';
                $user = $db->row($sql);

                $fields = 'IFNULL(sum(betcoin),0) AS betcoin,IFNULL(sum(coin),0) AS reds,IFNULL(sum(ticket),0) as ticket,IFNULL(sum(winerprofit),0) as winer,IFNULL(sum(profit),0) as profit';
                $where = 'uid=' . $uid . ' AND state=1 AND `times`<='.$TWL['todayEnd'];
                $tablename = $db_prefix . 'betslog';

                $sql = "SELECT {$fields} from {$tablename} where {$where}";
                $data = $db->row($sql);
                # 总共发送的红包金额
                $sql = 'SELECT IFNULL(sum(coin),0) AS coin,IFNULL(sum(redcoin),0) as redcoin from ' . $db_prefix . 'bets where uid=' . $uid . ' AND state=1 AND `begintimes`<='.$TWL['todayEnd'];
                $bets = $db->row($sql);

                # --------------------------- 统计发包数和发包金额 Begin ------------------------------

                $showFields = 'g.`establishcoin`,g.`title`,IFNULL(count1,0) AS count,IFNULL(_COIN,0) AS cointotal';
                $joinFields = 'l.`gameid`,COUNT(1) AS count1,IFNULL(SUM(`coin`),0) AS _COIN';
                # 今日发包数和发包金额
                $timeWhere = ' `begintimes`>=' . $TWL['todayBegin'] . ' AND `begintimes`<=' . $TWL['todayEnd'];
                /*
                $sql = 'SELECT COUNT(1) AS _NUM,IFNULL(SUM(coin),0) AS _COIN  from ' . $db_prefix . 'bets where uid=' . $uid . ' AND state=1'.$timeWhere;
                */
                $sql = 'SELECT ' . $showFields . ' FROM `' . $db_prefix . 'games` g LEFT JOIN (SELECT ' . $joinFields . ' FROM `' . $db_prefix . 'bets` l WHERE l.`uid`=' . $uid . ' AND l.`state`=1 AND ' . $timeWhere . ' GROUP BY l.`gameid`) t1 ON t1.`gameid`=g.`id`';
                $send_today = $db->query($sql);

                # 昨日发包数和发包金额
                $timeWhere = ' `begintimes`>=' . $TWL['yesTodayBegin'] . ' AND `begintimes`<=' . $TWL['yesTodayEnd'];
                $sql = 'SELECT ' . $showFields . ' FROM `' . $db_prefix . 'games` g LEFT JOIN (SELECT ' . $joinFields . ' FROM `' . $db_prefix . 'bets` l WHERE l.`uid`=' . $uid . ' AND l.`state`=1 AND ' . $timeWhere . ' GROUP BY l.`gameid`) t1 ON t1.`gameid`=g.`id`';
                $send_yestoday = $db->query($sql);

                # 总发包数和发包金额
                if(!$isToday) {
                    $timeWhere = ' AND l.`begintimes`<='.$TWL['todayEnd'];
                }else{
                    $timeWhere = '';
                }
                $sql = 'SELECT ' . $showFields . ' FROM `' . $db_prefix . 'games` g LEFT JOIN (SELECT ' . $joinFields . ' FROM `' . $db_prefix . 'bets` l WHERE l.`uid`=' . $uid . ' AND l.`state`=1 '.$timeWhere.' GROUP BY l.`gameid`) t1 ON t1.`gameid`=g.`id`';
                $send_total = $db->query($sql);

                # --------------------------- 统计发包数 End ----------------------------------------

                # --------------------------- 统计参与数和发包金额 Begin ------------------------------

                $showFields = 'g.`establishcoin`,g.`title`,IFNULL(count1,0) AS count,IFNULL(_BETCOIN,0) AS betcoin,IFNULL(_GRABCOIN,0) AS grab,IFNULL(_TICKET,0) AS ticket,IFNULL(_WINERPROFIT,0) AS winerprofit,IFNULL(_PROFIT,0) AS profit';
                $joinFields = 'l.`gameid`,COUNT(1) AS count1,IFNULL(SUM(`betcoin`),0) AS _BETCOIN,IFNULL(SUM(`coin`),0) AS _GRABCOIN,IFNULL(SUM(`ticket`),0) AS _TICKET,IFNULL(SUM(`winerprofit`),0) AS _WINERPROFIT,IFNULL(SUM(`profit`),0) AS _PROFIT';
                # 今日发包数和发包金额
                $timeWhere = ' `times`>=' . $TWL['todayBegin'] . ' AND `times`<=' . $TWL['todayEnd'];
                /*
                $sql = 'SELECT COUNT(1) AS _NUM,IFNULL(SUM(coin),0) AS _COIN  from ' . $db_prefix . 'bets where uid=' . $uid . ' AND state=1'.$timeWhere;
                */
                $sql = 'SELECT ' . $showFields . ' FROM `' . $db_prefix . 'games` g LEFT JOIN (SELECT ' . $joinFields . ' FROM `' . $db_prefix . 'betslog` l WHERE l.`uid`=' . $uid . ' AND l.`state`=1 AND ' . $timeWhere . ' GROUP BY l.`gameid`) t1 ON t1.`gameid`=g.`id`';
                $grab_today = $db->query($sql);

                # 昨日发包数和发包金额
                $timeWhere = ' `times`>=' . $TWL['yesTodayBegin'] . ' AND `times`<=' . $TWL['yesTodayEnd'];
                $sql = 'SELECT ' . $showFields . ' FROM `' . $db_prefix . 'games` g LEFT JOIN (SELECT ' . $joinFields . ' FROM `' . $db_prefix . 'betslog` l WHERE l.`uid`=' . $uid . ' AND l.`state`=1 AND ' . $timeWhere . ' GROUP BY l.`gameid`) t1 ON t1.`gameid`=g.`id`';
                $grab_yestoday = $db->query($sql);

                # 总发包数和发包金额
                if(!$isToday) {
                    $timeWhere = ' AND l.`times`<='.$TWL['todayEnd'];
                }else{
                    $timeWhere = '';
                }
                $sql = 'SELECT ' . $showFields . ' FROM `' . $db_prefix . 'games` g LEFT JOIN (SELECT ' . $joinFields . ' FROM `' . $db_prefix . 'betslog` l WHERE l.`uid`=' . $uid . ' AND l.`state`=1 '.$timeWhere.' GROUP BY l.`gameid`) t1 ON t1.`gameid`=g.`id`';
                $grab_total = $db->query($sql);

                # --------------------------- 统计参与数和发包金额 End ------------------------------

                # 除五人对战外的发包金额
                $sql = 'SELECT IFNULL(sum(redcoin),0) as redcoin from ' . $db_prefix . 'bets where uid=' . $uid . ' AND `gameid`<>1 AND state=1 AND `begintimes`<='.$TWL['todayEnd'];
                $bets0 = $db->row($sql);
                # 找出玩家等级信息 - userlevel
                $sql = 'SELECT `title` from `' . $db_prefix . 'userlevel` where lid=' . $user['userlevel'];
                $userlevel = $db->row($sql);

                # 充值总额
                $sql = 'SELECT IFNULL(SUM(`amount`),0) AS amount from `' . $db_prefix . 'users_recharge` where `uid`='.$uid.' AND `state`=1 AND `actiontime`<=' . $TWL['todayEnd'];
                $recharge = $db->row($sql);
                $data['rechargecoin'] = $recharge['amount'];
                # 提现总额
                $sql = 'SELECT IFNULL(SUM(`amount`),0) AS amount from `' . $db_prefix . 'users_cash` where `uid`='.$uid.' AND `state`=1 AND `cashtime`<=' . $TWL['todayEnd'];
                $cash = $db->row($sql);
                # 传包总额
                $sql = 'SELECT IFNULL( SUM( `coin` ), 0 ) AS _TOTAL FROM `' . $db_prefix . 'transfer_log` WHERE `touid` = ' . $uid . ' AND `times`<=' . $TWL['todayEnd'];
                $cashtouno = $db->row($sql);
                $sql = 'SELECT IFNULL( SUM( `coin` ), 0 ) AS _TOTAL FROM `' . $db_prefix . 'transfer_log` WHERE `fromuid` = ' . $uid . ' AND `times`<=' . $TWL['todayEnd'];
                $cashfromuno = $db->row($sql);
                # 发包总额
                $data['cashcoin'] = $cash['amount'];
                $data['profit'] = $utility->formatCoin(floatval($data['profit']) - floatval($bets0['redcoin']));
                $data['betscoin'] = $bets['coin'];
                $data['redcoin'] = $bets['coin'];//$bets['redcoin'];
                $data['userlevel'] = $userlevel['title'];
                $data['coin'] = $user['coin'];
                $data['cashfromuno'] = $cashfromuno['_TOTAL'];
                $data['cashtouno'] = $cashtouno['_TOTAL'];

                $send_today_establishcoin = 0;
                $send_yestoday_establishcoin = 0;
                $send_total_establishcoin = 0;

                $send_today_count = 0;
                $send_yestoday_count = 0;
                $send_total_count = 0;

                $send_today_cointotal = 0;
                $send_yestoday_cointotal = 0;
                $send_total_cointotal = 0;
                foreach ($send_today as $k=>$v){
                    $send_today[$k]['establishcoin'] = $v['establishcoin'] * $v['count'];
                    $send_today_establishcoin += $v['establishcoin'] * $v['count'];
                    $send_today_count += $v['count'];
                    $send_today_cointotal += $v['cointotal'];
                }
                $send_today[] = [
                    'title' => '合计',
                    'establishcoin' => $send_today_establishcoin,
                    'count' => $send_today_count,
                    'cointotal' => $send_today_cointotal
                ];
                foreach ($send_yestoday as $k=>$v){
                    $send_yestoday[$k]['establishcoin'] = $v['establishcoin'] * $v['count'];
                    $send_yestoday_establishcoin += $v['establishcoin'] * $v['count'];
                    $send_yestoday_count += $v['count'];
                    $send_yestoday_cointotal += $v['cointotal'];
                }
                $send_yestoday[] = [
                    'title' => '合计',
                    'establishcoin' => $send_yestoday_establishcoin,
                    'count' => $send_yestoday_count,
                    'cointotal' => $send_yestoday_cointotal
                ];
                foreach ( $send_total as $k=>$v ){
                    $send_total[$k]['establishcoin'] = $v['establishcoin'] * $v['count'];
                    $send_total_establishcoin += $v['establishcoin'] * $v['count'];
                    $send_total_count += $v['count'];
                    $send_total_cointotal += $v['cointotal'];
                }
                $send_total[] = [
                    'title' => '合计',
                    'establishcoin' => $send_total_establishcoin,
                    'count' => $send_total_count,
                    'cointotal' => $send_total_cointotal
                ];
                $data['send'] = array(
                    'today' => $send_today,
                    'yestoday' => $send_yestoday,
                    'total' => $send_total,
                );

                $grab_today = self::preGrabStatisticsData($grab_today);
                $grab_yestoday = self::preGrabStatisticsData($grab_yestoday);
                $grab_total = self::preGrabStatisticsData($grab_total);

                $data['grab'] = array(
                    'today' => $grab_today,
                    'yestoday' => $grab_yestoday,
                    'total' => $grab_total,
                );
                $data['today'] = date('Y-m-d', $TWL['todayBegin']);
                $data['yestoday'] = date('Y-m-d', $TWL['yesTodayBegin']);

                # 系统参数
                //$data['iosaudit'] = intval($utility->getSystemParams('iosaudit'));
                $data['times'] = date('Y-m-d H:i:s', time());
                if(!$isToday){
                    $data['times'] = date('Y-m-d', $searchTime);
                    $insertFields = array(
                        'uid' => $uid,
                        'actiontimes' => $TWL['todayBegin'],
                        'jsonvalue' => json_encode($data),
                    );
                    $db->insert(\Config\Sys::$dbprefix.'st')->cols($insertFields)->query();
                }
                $utility->redisSetEx($redis_key, $data, 300); // 缓存有效期为120秒
                # 保存到数据库中
            }
        }else{
            $jsonvalue = $searchData['jsonvalue'];
            $data = json_decode($jsonvalue, true);
        }
        $data['consuming'] = 5;
        return $data;
    }
    public static function statisticsForUid($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        # "ps","pc",'begintimes','endtimes','state','gameid'
        $url_args = array(
            'cmd',
            'token',
            'begintimes',
            'uno',
            'remoteip',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']==200){
            $uid = $user['uid'];
            $searchTimes = ((empty($paras['begintimes']) ? time() : strtotime($paras['begintimes'])));
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'datas' => self::statisticsAgentForUid($uid, $searchTimes),
            );
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }

    public static function preGrabStatisticsData($data)
    {
        $grab_count = 0;
        $grab_betcoin = 0;
        $grab_grab = 0;
        $grab_ticket = 0;
        $grab_winerprofit = 0;
        $grab_profit = 0;
        foreach ( $data as $k=>$v ){
            unset($data[$k]['establishcoin']);
            $grab_count += $v['count'];
            $grab_betcoin += $v['betcoin'];
            $grab_grab += $v['grab'];
            $grab_ticket += $v['ticket'];
            $grab_winerprofit += $v['winerprofit'];
            $grab_profit += $v['profit'];
        }
        $data[] = [
            'title' => '合计',
            'count' => $grab_count,
            'betcoin'=> $grab_betcoin,
            'grab'  => $grab_grab,
            'ticket'=> $grab_ticket,
            'winerprofit' => $grab_winerprofit,
            'profit'=> $grab_profit
        ];
        return $data;
    }

    # endregion

    # region 拉取玩家的站内信息
    public static function getUserMailList($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'state',
        );
        $paras = $utility->get_url_args($paras, $url_args);

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']!=200){
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }


        $page_args = $utility->get_page_args($paras, $url_args);
        $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);


        $uid = $user['uid'];
        $fields = 'l.`id`,l.`title`,FROM_UNIXTIME(l.`actiontime`) AS actiontime,u.`status`';
        $where_txt = 'l.id=u.forid AND l.`status`<2 AND u.uid='.$uid;
//        $state = 1;
//        if(!empty($paras['state'])) $state  = $paras['state'];
//        if($state!='') $where_txt .= " AND u.`status`=".$state;

        if(!empty($paras['state'])) $where_txt .= " AND u.`status`=".$paras['state'];

        $tablename = \Config\Sys::$dbprefix.'mailbox_user u,'.\Config\Sys::$dbprefix.'mailbox l';

        $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";

        $sql_arr = array(
            'field' => $fields,
            'page_current' => $paras['pc'],
            'pagesize' => $_pagesize,
            'order' => ' ORDER BY `status` ASC,`id` DESC',
        );
        $datas = $utility->getTableRows($sql, $sql_arr);
        return array(
            'state' => 200,
            'cmd' => $paras['cmd'],
            'datas' => $datas['datas'],
            'curpage' => intval($paras['pc']),
            'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
        );

    }
    # endregion

    # region 拉取玩家站内信息 - 内容
    public static function getUserMailItem($paras)
    {
        global $db;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'mailid|N',
            'remoteip',
        );

        $paras = $utility->get_url_args($paras, $url_args);
        if(empty($paras['mailid'])){
            return array(
                'state' => 404,
                'cmd' => $paras['cmd'],
                'msgid' => 404,
            );
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']!=200){
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }

        $uid = $user['uid'];
        $mailid = $paras['mailid'];

        $fields = 'l.`title`,l.`actiontime`,c.`content`';
        $where = 'l.id=u.forid AND l.`status`<2 AND u.`status`<2 AND c.`forid`=l.`id` AND l.`id`='.$mailid.' AND u.uid='.$uid;
        $tablename = \Config\Sys::$dbprefix.'mailbox_user u,'.\Config\Sys::$dbprefix.'mailbox l,'.\Config\Sys::$dbprefix.'mailbox_content c';
        $sql = "SELECT {$fields} FROM {$tablename} WHERE {$where}";
        $datas = $db->row($sql);
        $datas['actiontime'] = $utility->formatTimes($datas['actiontime']);
        # 更新为已读
        $db->query("UPDATE ".\Config\Sys::$dbprefix."mailbox_user SET status=1 WHERE forid=".$mailid." AND uid=".$user['uid']." LIMIT 1");
        return array(
            'state' => 200,
            'cmd' => $paras['cmd'],
            'datas' => $datas,
        );

    }
    # endregion

    # region 跑马灯内容
    public static function getMarquee($paras)
    {
        global $utility;
        return $utility->getMarquees($paras);
    }
    # endregion

    # region 用户签到送积分
    public static function signGiveScore($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
        );
        $paras = $utility->get_url_args($paras, $url_args);
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']!=200){
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        $uid = $user['uid'];
        # 检测是否已签到
        $begintime = strtotime(date('Y-m-d',time()));
        $endtime = $begintime + 86400;

        $givescore = $utility->getSystemParams('givescore');

        $sql = 'SELECT COUNT(1) AS __TOTAL FROM `'.\Config\Sys::$dbprefix.'scorelog` WHERE `uid`='.$uid.' AND `liqtype`=2 AND `times` BETWEEN '.$begintime.' AND '.$endtime;
        $signtotal = $db->row($sql);
        $signtotal = $signtotal['__TOTAL'];
        if($signtotal>0){
            return array(
                'cmd' => 'signline',
                'state' => 404,
                'msgid' => 10075,
            );
        }
        $totalgivescore = 0;
        if(floatval($givescore)>0){
            $utility->setScore(
                array(
                    'uid' => $uid,
                    'score' => floatval($givescore),
                    'gameid' => 0,
                    'liqtype' => 2,
                )
            );
            $totalgivescore = $totalgivescore + $givescore;
        }
        $givescoredays = $utility->getSystemParams('givescoredays');
        $givescoremore =  $utility->getSystemParams('givescoremore');

        $endtime = time();
        $begintime = time() - ( 5 * 86400);
        $sql = 'SELECT COUNT(1) AS __TOTAL FROM `'.\Config\Sys::$dbprefix.'scorelog` WHERE `uid`='.$uid.' AND `liqtype`=2 AND `times` BETWEEN '.$begintime.' AND '.$endtime;
        $signtotal = $db->row($sql);

        $signtotal = $signtotal['__TOTAL'];
        if($signtotal >= $givescoredays){
            $utility->setScore(
                array(
                    'uid' => $uid,
                    'score' => floatval($givescoremore),
                    'gameid' => 0,
                    'liqtype' => 2,
                    'ex3' => '连续5天及以上',
                )
            );
            $totalgivescore = $totalgivescore + $givescoremore;
        }
        return array(
            'state' => 200,
            'cmd' => 'signline',
            'msgid' => 10076,
            'score' => $totalgivescore,
            'usercoin' => $user['usercoin'],
            'userscore' => $user['userscore'] + $totalgivescore,
        );
    }
    # endregion

    # region 下级用户
    public static function lowerLevelUserItem($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'uno',
        );
        $paras = $utility->get_url_args($paras, $url_args);
        if(empty($paras['uno'])){
            return array(
                'state' => 404,
                'cmd' => $paras['cmd'],
                'msgid' => 10000,
            );
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if($user['state']!=200){
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }

        # 检测指定的UNO是否为自己的直属玩家
        $sql = "SELECT `uid` FROM `".\Config\Sys::$dbprefix."users` WHERE `uno`='".$paras['uno']."' AND `parentid`=".$user['uid'];
        $lowerUser = $db->row($sql);
        if(!$lowerUser){
            return array(
                'state' => 404,
                'cmd' => $paras['cmd'],
                'msgid' => 10000,
            );
        }
        # 统计
        $statistics = self::statisticsAgentForUid($lowerUser['uid']);
        unset($lowerUser['uid']);
        return array(
            'cmd'=>$paras['cmd'],
            'state' => 200,
            'datas' => $statistics,
        );
    }

    public static function lowerLevelUser($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
            'ps',
            'pc|N|1',
            'begintimes',
            'endtimes',
            'uno',
            'usertype',
            't',
        );

        $paras = $utility->get_url_args($paras, $url_args);
        $user = $utility->exitsToKen($paras['token'], $paras['cmd']);

        if ($user['state'] != 200) {
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        $parentid = $user['uid'];
        $_pagesize = (empty($paras['ps']) ? \Config\Sys::$pagesize : $paras['ps']);

        $where_txt = "u.`parentid`=" . $parentid;

        if (!empty($paras['uno'])) $where_txt .= " AND u.`uno` = '" . $paras['uno'] . "'";
        if ($paras['usertype'] != '') $where_txt .= " AND u.`usertype`= " . $paras['usertype'];

        $begintimes = strtotime('1999-12-20');
        $endtimes = time();

        if (!empty($paras['begintimes'])) $begintimes = strtotime($paras['begintimes']);
        if (!empty($paras['endtimes'])) $endtimes = strtotime($paras['endtimes']) + 86400;

        if(!empty($paras['t'])){
            $TWL = $utility->getTWLTimes();
            switch (strtolower($paras['t'])){
                case 'today':
                    $begintimes = $TWL['todayBegin'];
                    $endtimes = $TWL['todayEnd'];
                    break;
                case "yestoday":
                    $begintimes = $TWL['yesTodayBegin'];
                    $endtimes = $TWL['yesTodayEnd'];
                    break;
                case 'week':
                    $begintimes = $TWL['weekBegin'];
                    $endtimes = $TWL['weekEnd'];
                    break;
                case 'lastweek':
                    $begintimes = $TWL['lastWeekBegin'];
                    $endtimes = $TWL['lastWeekEnd'];
                    break;
                case 'month':
                    $begintimes = $TWL['monthBegin'];
                    $endtimes = $TWL['monthEnd'];
                    break;
            }
        }

        // $where_txt .= ' AND u.`regtimes` >= ' . $begintimes . ' AND u.`regtimes` <= ' . $endtimes;
        $tablename = \Config\Sys::$dbprefix . 'users u';

        $sql = "SELECT ~field~ FROM {$tablename} WHERE {$where_txt} ~order~ ~limit~";
        # 取出当前页的数据字段、当前页、每页显示数、排序
        $fields = "u.`uno`,u.`nickname`,u.`usertype`,FROM_UNIXTIME(u.`regtimes`) AS regtimes,`avatar`,`betcoin`,`recharge`,`rebate`,";
        $fields .= "`coin`,`profit`,";
        //$fields .= "(SELECT IFNULL(SUM(c.`amount`),0) FROM `rp_users_cash` c WHERE c.`uid`=u.`uid` AND c.`state`=1) AS cashcoin,";
        $fields .= "( SELECT IFNULL( SUM( b.`coin` ), 0 ) FROM `".\Config\Sys::$dbprefix."backcoin` b WHERE b.`fromuid` = u.`uid` AND b.`actiontime`>=".$begintimes." AND b.`actiontime`<=".$endtimes.") AS outbackcoin";
        $sql_arr = array(
            'field' => $fields,
            'page_current' => $paras['pc'],
            'pagesize' => $_pagesize,
            'order' => ' ORDER BY outbackcoin DESC',
        );
        $datas = $utility->getTableRows($sql, $sql_arr);

        $sql = "SELECT IFNULL( SUM( b.`coin` ), 0 ) AS _total FROM `".\Config\Sys::$dbprefix."backcoin` b WHERE b.`uid` = ".$user['uid']." AND b.`actiontime`>=".$begintimes." AND b.`actiontime`<=".$endtimes;
        $backcoin = $db->row($sql);


        $result = array(
            'state' => 200,
            'cmd' => $paras['cmd'],
            'datas' => $datas['datas'],
            'backcointotal' => $backcoin['_total'],
            'record' => intval($datas['total']),
            'curpage' => intval($paras['pc']),
            'maxpage' => $utility->get_maxpage($_pagesize, $datas['total']),
            'urlparas' => http_build_query($paras),
        );
        return $result;
    }
    # endregion

    # region 我的团队统计信息
    public static function myTeamInfo_delete($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
        );

        $paras = $utility->get_url_args($paras, $url_args);
        $user = $utility->exitsToKen($paras['token'], $paras['cmd']);

        if ($user['state'] != 200) {
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }

        # 不是代理不用返回统计数据
        if($user['usertype'] == 0){
            return array(
                'state' => 404,
                'cmd' => $paras['cmd'],
                'msgid' => 10103,
            );
        }

        $redisKey = \Config\Sys::$redisKey['LUCONT'].$user['uid'];

        $result = $utility->redisGet($redisKey);
        if(!$result) {

            $TWL = $utility->getTWLTimes();

            # 今日的开始和结束时间
            $beginToday = $TWL['todayBegin'];//mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday = $TWL['todayEnd'];//mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;

            # 本周开始和结束的时间戳
            $weekBeginTimes = $TWL['weekBegin'];//strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
            $weekEndTimes = $TWL['weekEnd'];//strtotime(date('Y-m-d', strtotime("this week Sunday", $timestamp))) + 24 * 3600 - 1;

            # 上周开始和结束的时间戳
            $lastWeekBeginTimes = $TWL['lastWeekBegin'];//strtotime(date('Y-m-d', strtotime("last week Monday", $timestamp)));
            $lastWeekEndTimes = $TWL['lastWeekEnd'];//strtotime(date('Y-m-d', strtotime("last week Sunday", $timestamp))) + 24 * 3600 - 1;

            # 要统计的字段
            $totalFields = "COUNT(`uid`) AS total,IFNULL(SUM(`betcoin`),0) AS betcoin,IFNULL(SUM(`profit`),0) AS profit,IFNULL(SUM(`backtotal`),0) AS backtotal";
            $totalTable = "`" . \Config\Sys::$dbprefix . "users`";
            # 找出当前用户的直属团队用户的统计信息
            $sql = "SELECT " . $totalFields . " FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " LIMIT 1";
            $directTeam = $db->row($sql);

            # 找出本周直属团队用户的统计信息
            $sql = "SELECT IFNULL(SUM(l.betcoin),0) AS betcoin,IFNULL(SUM(l.profit),0) AS profit From rp_betslog l, rp_users u WHERE u.parentid=" . $user['uid'] . " AND l.times>=" . $weekBeginTimes . " AND l.`times`<=" . $weekEndTimes . " AND l.uid=u.uid";
            $weekDirectTeam = $db->row($sql);

            # 找出上周直属团队用户的统计信息
            $sql = "SELECT IFNULL(SUM(l.betcoin),0) AS betcoin,IFNULL(SUM(l.profit),0) AS profit From rp_betslog l, rp_users u WHERE u.parentid=" . $user['uid'] . " AND l.times>=" . $lastWeekBeginTimes . " AND l.`times`<=" . $lastWeekEndTimes . " AND l.uid=u.uid";
            $lastWeekDirectTeam = $db->row($sql);

            # 今日新进人员
            $sql = "SELECT COUNT(uid) AS _total FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " AND `regtimes`>=" . $beginToday . " AND `regtimes`<=" . $endToday . " AND `usertype`>0 LIMIT 1";
            $todayUserCount = $db->row($sql);
            # 本周新进人员
            $sql = "SELECT COUNT(uid) AS _total FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " AND `regtimes`>=" . $weekBeginTimes . " AND `regtimes`<=" . $weekEndTimes . " AND `usertype`>0 LIMIT 1";
            $weekUserCount = $db->row($sql);
            # 上周新进人员
            $sql = "SELECT COUNT(uid) AS _total FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " AND `regtimes`>=" . $lastWeekBeginTimes . " AND `regtimes`<=" . $lastWeekEndTimes . " AND `usertype`>0 LIMIT 1";
            $lastWeekUserCount = $db->row($sql);

            # 找出玩家代理等级信息 - agentlevel
            $sql = 'SELECT `lid`,`title` from `' . \Config\Sys::$dbprefix . 'agentlevel` where lid=' . $user['agentlevel'];
            $agentlevel = $db->row($sql);
            $datas['agentlevel'] = $agentlevel['title'];
            $datas['agentlid'] = $agentlevel['lid'];

            # 离下次升级还差的人数或返水(受邀请人需要有充值和有效参与流水)
            $sql = 'SELECT `backtotal`,`agentlevel`,(SELECT COUNT(1) FROM `' . \Config\Sys::$dbprefix . 'users` WHERE `betcoin`>0 AND `recharge`>0 AND `parentid`=' . $user['uid'] . ') AS myuserscount,(SELECT IFNULL(`backtotal`,0) FROM `' . \Config\Sys::$dbprefix . 'agentlevel` WHERE `lid`=' . ($user['agentlevel'] + 1) . ') AS nextagenlevel FROM `' . \Config\Sys::$dbprefix . 'users` WHERE `uid`=' . $user['uid'] . ' LIMIT 1';
            $nextagentlevel = $db->row($sql);
            $nextagentbacktotal = $nextagentlevel['nextagenlevel'] - $nextagentlevel['backtotal'];
            $datas['nextagent'] = ($nextagentbacktotal > 0 ? $nextagentbacktotal : 0);
            $datas['backtotal'] = $nextagentlevel['backtotal'];
            $datas['upagentnumbers'] = intval($utility->getSystemParams('upagentnumbers')) - $nextagentlevel['myuserscount'];


            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'cachetimes' => date('Y-m-d H:i:s', time()),
                'user' => array(
                    'backtotal' => $user['backtotal'],
                ),
                'directteam' => $directTeam,
                'week' => $weekDirectTeam,
                'lastweek' => $lastWeekDirectTeam,
                'newcomers' => array(
                    'today' => $todayUserCount['_total'],
                    'week' => $weekUserCount['_total'],
                    'lastweek' => $lastWeekUserCount['_total'],
                ),
                'agent' => array(
                    'agentlevel' => $datas['agentlevel'],
                    'agentlid' => $datas['agentlid'],
                    'backtotal' => $utility->formatCoin($datas['backtotal'], 2),
                    'nextagent' => $utility->formatCoin($datas['nextagent'], 2),
                    'upagentnumbers' => $datas['upagentnumbers'],
                ),
            );
            $utility->redisSetEx($redisKey, $result, 300);
        }
        return $result;


    }
    public static function myTeamInfo($paras)
    {
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'token',
            'remoteip',
        );

        $paras = $utility->get_url_args($paras, $url_args);
        $user = $utility->exitsToKen($paras['token'], $paras['cmd']);

        if ($user['state'] != 200) {
            return array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }

        # 不是代理不用返回统计数据
        if($user['usertype'] == 0){
            return array(
                'state' => 404,
                'cmd' => $paras['cmd'],
                'msgid' => 10103,
            );
        }

        $redisKey = \Config\Sys::$redisKey['LUCONT'].$user['uid'];

        $result = $utility->redisGet($redisKey);
        if(!$result) {

            $TWL = $utility->getTWLTimes();

            # 今日的开始和结束时间
            $beginToday = $TWL['todayBegin'];//mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday = $TWL['todayEnd'];//mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;

            # 本周开始和结束的时间戳
            $weekBeginTimes = $TWL['weekBegin'];//strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
            $weekEndTimes = $TWL['weekEnd'];//strtotime(date('Y-m-d', strtotime("this week Sunday", $timestamp))) + 24 * 3600 - 1;

            # 上周开始和结束的时间戳
            $lastWeekBeginTimes = $TWL['lastWeekBegin'];//strtotime(date('Y-m-d', strtotime("last week Monday", $timestamp)));
            $lastWeekEndTimes = $TWL['lastWeekEnd'];//strtotime(date('Y-m-d', strtotime("last week Sunday", $timestamp))) + 24 * 3600 - 1;

            # 要统计的字段
            $totalFields = "COUNT(`uid`) AS total,IFNULL(SUM(`betcoin`),0) AS betcoin,IFNULL(SUM(`profit`),0) AS profit,IFNULL(SUM(`backtotal`),0) AS backtotal";
            $totalTable = "`" . \Config\Sys::$dbprefix . "users`";
            # 找出当前用户的直属团队用户的统计信息
            $sql = "SELECT " . $totalFields . " FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " LIMIT 1";
            $directTeam = $db->row($sql);

            # 找出本月直属团队用户的有效参与和盈亏统计信息
            $sql = "SELECT IFNULL(SUM(l.betcoin),0) AS betcoin,IFNULL(SUM(l.profit),0) AS profit From rp_betslog l, rp_users u WHERE u.parentid=" . $user['uid'] . " AND l.times>=" . $TWL['monthBegin'] . " AND l.`times`<=" . $TWL['monthEnd'] . " AND l.uid=u.uid";
            $monthDirectTeam = $db->row($sql);

            # 今日新进人员
            $sql = "SELECT COUNT(uid) AS _total FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " AND `regtimes`>=" . $beginToday . " AND `regtimes`<=" . $endToday . " AND `usertype`>0 LIMIT 1";
            $todayUserCount = $db->row($sql);
            # 本周新进人员
            $sql = "SELECT COUNT(uid) AS _total FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " AND `regtimes`>=" . $weekBeginTimes . " AND `regtimes`<=" . $weekEndTimes . " AND `usertype`>0 LIMIT 1";
            $weekUserCount = $db->row($sql);
            # 本月新进人员
            $sql = "SELECT COUNT(uid) AS _total FROM " . $totalTable . " WHERE `parentid`=" . $user['uid'] . " AND `regtimes`>=" . $TWL['monthBegin'] . " AND `regtimes`<=" . $TWL['monthEnd'] . " AND `usertype`>0 LIMIT 1";
            $monthUserCount = $db->row($sql);

            # 代理佣金统计 SQL
            $backCoin = array(
                'today' => 0,
                'yestoday' => 0,
                'week' => 0,
                'month' => 0,
            );
            $_sql = "SELECT IFNULL(SUM(coin),0) AS _total FROM `" . \Config\Sys::$dbprefix . "backcoin` WHERE `uid`=".$user['uid']." AND ";
            # 今日 - 代理佣金
            $sql = $_sql . "`actiontime`>=".$TWL['todayBegin']." AND `actiontime`<=".$TWL['todayEnd'];
            $backCoin['today'] = $db->row($sql);
            $backCoin['today'] = $backCoin['today']['_total'];
            # 昨日 - 代理佣金
            $sql = $_sql . "`actiontime`>=".$TWL['yesTodayBegin']." AND `actiontime`<=".$TWL['yesTodayEnd'];
            $backCoin['yestoday'] = $db->row($sql);
            $backCoin['yestoday'] = $backCoin['yestoday']['_total'];
            # 本周 - 代理佣金
            $sql = $_sql . "`actiontime`>=".$TWL['weekBegin']." AND `actiontime`<=".$TWL['weekEnd'];
            $backCoin['week'] = $db->row($sql);
            $backCoin['week'] = $backCoin['week']['_total'];
            # 本月 - 代理佣金
            $sql = $_sql . "`actiontime`>=".$TWL['monthBegin']." AND `actiontime`<=".$TWL['monthEnd'];
            $backCoin['month'] = $db->row($sql);
            $backCoin['month'] = $backCoin['month']['_total'];


            # 找出玩家代理等级信息 - agentlevel
            $sql = 'SELECT `lid`,`title` from `' . \Config\Sys::$dbprefix . 'agentlevel` where lid=' . $user['agentlevel'];
            $agentlevel = $db->row($sql);
            $datas['agentlevel'] = $agentlevel['title'];
            $datas['agentlid'] = $agentlevel['lid'];

            # 离下次升级还差的人数或返水(受邀请人需要有充值和有效参与流水)
            $sql = 'SELECT `backtotal`,`agentlevel`,(SELECT COUNT(1) FROM `' . \Config\Sys::$dbprefix . 'users` WHERE `betcoin`>0 AND `recharge`>0 AND `parentid`=' . $user['uid'] . ') AS myuserscount,(SELECT IFNULL(`backtotal`,0) FROM `' . \Config\Sys::$dbprefix . 'agentlevel` WHERE `lid`=' . ($user['agentlevel'] + 1) . ') AS nextagenlevel FROM `' . \Config\Sys::$dbprefix . 'users` WHERE `uid`=' . $user['uid'] . ' LIMIT 1';
            $nextagentlevel = $db->row($sql);
            $nextagentbacktotal = $nextagentlevel['nextagenlevel'] - $nextagentlevel['backtotal'];
            $datas['nextagent'] = ($nextagentbacktotal > 0 ? $nextagentbacktotal : 0);
            $datas['backtotal'] = $nextagentlevel['backtotal'];
            $datas['upagentnumbers'] = intval($utility->getSystemParams('upagentnumbers')) - $nextagentlevel['myuserscount'];


            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'cachetimes' => date('Y-m-d H:i:s', time()),
                'user' => array(
                    'backtotal' => $user['backtotal'],
                ),
                'directteam' => $directTeam,
                'backcoin' => $backCoin,
                'monthDirectTeam' => array(
                    'betcoin' => $monthDirectTeam['betcoin'],
                    'profit' => $monthDirectTeam['profit'],
                ),
                'newcomers' => array(
                    'today' => $todayUserCount['_total'],
                    'week' => $weekUserCount['_total'],
                    'month' => $monthUserCount['_total'],
                ),
                'agent' => array(
                    'agentlevel' => $datas['agentlevel'],
                    'agentlid' => $datas['agentlid'],
                    'backtotal' => $utility->formatCoin($datas['backtotal'], 2),
                    'nextagent' => $utility->formatCoin($datas['nextagent'], 2),
                    'upagentnumbers' => $datas['upagentnumbers'],
                ),
            );
            $utility->redisSetEx($redisKey, $result, 300);
        }
        return $result;


    }
    # endregion

    # region 代理等级列表
    public static function agentLevelList($paras)
    {
        global $utility;
        $result = $utility->getAgentLevelList($paras);
        return [
            'state' => 200,
            'datas' => $result['agent'],
            'agentupdategiveway' => $result['agentupdategiveway'],
            'upagentnumbers'    => $result['upagentnumbers']
        ];
    }
    # endregion

    # region 单个代理等级数据
    public static function agentLevelForLid($paras)
    {
        global $utility;
        return $utility->getAgentLevelForLid($paras);
    }
    # endregion

    # region 用户等级列表
    public static function userLevelList($paras)
    {
        global $utility;
        return $utility->getUserLevelList($paras);
    }
    # endregion

    # region 单个用户等级数据
    public static function userLevelForLid($paras)
    {
        global $utility;
        return $utility->getUserLevelForLid($paras);
    }
    # endregion

    # region 发送手机短信验证码
    public static function sendVerifyToMobile($paras){
        global $db;
        global $redis;
        global $utility;

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'remoteip',
            'mobilenumber',
            'errorCode|N',
        );

        $paras = $utility->get_url_args($paras, $url_args);

        $result = array('state'=>404, 'msgid'=>404);

        if(empty($paras['mobilenumber'])){
            $result['msgid'] = 10061;
            return $result;
        }

        if(!$utility->isMobileNumber($paras['mobilenumber'])){
            $result['msgid'] = 10061;
            return $result;
        }

        $result = $utility->sendSMS($paras['mobilenumber']);
        return $result;
    }
    # endregion

    # region 创建房间
    public static function createRoom($paras)
    {
        global $db;
        global $utility;
        global $redis;

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);

        if( $user['state'] != 200 ){
            return [
                'state' => $user['state'],
                'cmd'   => $paras['cmd'],
                'msgid' => $user['msgid']
            ];
        }
        $paras['uid'] = $user['uid'];
        $now = time();
        $result = [
            'state' => 404,
            'cmd'   => $paras['cmd'],
            'msgid' => 404
        ];
        $insertData = [
            'name'      => $paras['name'],
            'game_id'   => $paras['game_id'],
            'uid'       => $paras['uid'],
            'createtimes' => $now,
            'endtimes'  => $now + intval($paras['time'] * 3600),
            'pass'      => $paras['pass']
        ];
        //新建房间
        $cid = $db->insert(\Config\Sys::$dbprefix.'rooms_game')->cols($insertData)->query();

        if( $cid ){
            $roomNum = date('Ymd',$insertData['createtimes']).'-'.$cid;

            $sendData = [
                'cmd'   => 'newroom',
                'state' => 200,
                'data'  => [
                    'id'        => $cid,
                    'name'      => $paras['name'],
                    'game_id'   => $paras['game_id'],
                    'uid'       => $paras['uid'],
                    'createtimes' => date('Y-m-d H:i:s',$insertData['createtimes']),
                    'endtimes'  => date('Y-m-d H:i:s',$insertData['endtimes']),
                    'room_num'  => $roomNum,
                    'status'    => 1
                ]
            ];
            Gateway::sendToGroup('room_'.$paras['game_id'],json_encode($sendData));
            return [
                'state' => 200,
                'cmd'   => $paras['cmd'],
                'room_num'  => $roomNum
            ];
        }else{
            $result['msgid'] = 10006;
            return $result;
        }
    }
    # endregion

    # region 注册机器人
    public static function importAuthendUser($args)
    {
        global $db;
        global $utility;
        $url_args = array(
            "cmd",
            "uno",
            "password",
            'nickname',
            'rebate|F',
            'usertype|N',
            'lid|N',
            'tel',
            'codeError',
            'verify',
            'codemobile',
            'remoteip',
            'client_type|N',
            'browser',
            'os',
            'gameid|N'
        );
        $paras = $utility->get_url_args($args, $url_args);
        $result = array('state'=>404,'msgid'=>404,'cmd'=>$paras['cmd']);
        if(empty($paras['tel']))
        {
            $result['msgid'] = 10061;//手机号码无效;
            echo "手机号码无效\n";
            return;
        }
        if(empty($paras['nickname'])){
            $result['msgid'] = 10009;//'用户名不能为空';
            echo "用户名不能为空\n";
            return;
        }
        if(empty($paras['password'])){
            $result['msgid'] = 10010;//'登录密码不能为空';
            echo "登录密码不能为空\n";
            return;

        }

        if(empty($paras['nickname'])){
            $result['msgid'] = 10009;//'用户名不能为空';
            echo "用户名不能为空\n";
            return;
        }
        if(empty($paras['password'])){
            $result['msgid'] = 10010;//'登录密码不能为空';
            echo "登录密码不能为空\n";
            return;
        }
        //检测手机号码是否已被注册
        $user = $db->row("SELECT `uid` AS _TOTAL FROM `rp_users` WHERE `tel`='{$paras['tel']}' AND `usertype`>0");
        if($user){
            $result['msgid'] = 10062;//'手机号码已绑定在其它玩家帐号';
            return $result;
        }
        //生成密码token
        $token = $utility->randString(4);
        $makePasswd = $utility->encrypt($paras['password'],'E',$token);
        $webtoken = $utility->settoken($paras['uno'], $token);

        # 随机头像
        $roundAvatar = $utility->roundAvatarList();
        $userAvatar = array_rand($roundAvatar);
        $insert_data = array(
            'uno' => $paras['uno'],
            'nickname'=>$paras['nickname'],
            'passwd'=>$makePasswd,
            'tel'=>$paras['tel'],
            'regtimes'=>time(),
            'regip'=>$paras['remoteip'],
            'rebate'=>$paras['rebate'],
            'usertype'=>$paras['usertype'],
            'lastlogintimes'=>time(),
            'token'=>$token,
            'webtoken'=>$webtoken,
            'avatar' => $roundAvatar[$userAvatar]['imgurl'],
            'parentid' => 0,
        );

        try {
            $db->beginTrans();
            $uid = $db->insert(\Config\Sys::$dbprefix . 'users')->cols($insert_data)->query();
            $autosend = [
                'uid'   => $uid,
                'gameid'=> $paras['gameid']
            ];
            $db->insert(\Config\Sys::$dbprefix . 'autosend')->cols($autosend)->query();
            echo "---注册成功{$uid}---\n";
            $db->commitTrans($paras['uno']);
        }catch (PDOException $e){
            echo '注册失败:'.$e->getMessage();
            $db->rollBackTrans();
        }
    }
    # endregion
}